-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsecure_drop.py
executable file
·325 lines (240 loc) · 8.59 KB
/
secure_drop.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
#!/usr/bin/env python3
import argparse # Command Line Argument Parser
import cmd # Supplies the subshell CMD prompt
import configparser # .ini-ish file config accessor/generators
import crypt # Many Crypt functions
import getpass # No echo prompt for password
import logging # Logging tools
import pathlib # Sane Path accessors/Validators
from datetime import timedelta # Datetime utils
# Constant time Hash compare that prevents the raw from ever being in memory
from hmac import compare_digest as comp_hash
# RSA tools
from Cryptodome.PublicKey import RSA
from timeloop import Timeloop # For async calls
from peerDetect import PeerDetect, StringPacket
# Configure logging
logger = logging.getLogger()
logger.propagate = True
logger.setLevel(logging.CRITICAL)
# Configure Argument Parsing
parser = argparse.ArgumentParser(description="Secure File Drop")
parser.add_argument('-c', '--config', action='store',
default='~/.config/secure_drop/config')
parser.add_argument('-d', '--debug', action='store_true', default=False)
args = parser.parse_args()
# Extract args
ConfigPath = args.config
DEBUG = args.debug
# Default config directory
CONFIGFILE = pathlib.Path(ConfigPath).expanduser()
CONFIGFILE.parent.mkdir(parents=True, mode=0o700, exist_ok=True)
CONFIGFILE.touch(mode=0o700, exist_ok=True)
# ######################## MAIN ######################## #
def main():
# Run Registration if not already done
if (not isRegistered()):
register()
cleanUpAndExit()
# Ask the user for login credentials
login()
# Enter Custom SubShell defined be Shell class
Shell().cmdloop()
# ######################## SHELL ######################## #
# Custom Shell class, Defines options available from command line
# Has built in help command which prints the text in first line
class Shell(cmd.Cmd):
intro = ''
prompt = 'Secure_Drop> '
def do_exit(self, args):
'Exit the program'
cleanUpAndExit()
def do_add(self, args):
'Add a new contact'
addContact()
def do_list(self, args):
'List all online contacts'
listOnlineContacts()
def do_send(self, args):
'Transfer a file to contact: SEND <contact_email> <filename>'
sendFile(args)
def addContact():
# Store in config file
newName = input('Enter full name: ')
newEmail = input('Enter email address: ')
config = readConfig()
name = config['Cred']['name']
# email = config['Cred']['email']
if (name == newName):
print("Invalid User. User already existed.")
else:
config['Contacts ' + newName] = {
'name': newName,
'email': newEmail,
}
writeConfig(config)
print("Contact added")
def listOnlineContacts():
print('Online Contacts: ')
for peer in peerDetect.getPeerList():
try:
if (doesContactExist(peer)):
contact = getContact(peer)
print("\t {} <{}>".format(contact['name'], contact['email']))
except KeyError:
pass
def sendFile(arg):
argsplit = arg.split()
if(len(argsplit) != 2):
print("Invalid argument count")
return
contact, filepath = argsplit
# ARG 1 must be a contact
if (not doesContactExist(contact)):
print("'{}' is not a known contact, "
"maybe you need to add them with add?".format(contact))
return
# ARG 2 must be a valid file
file = pathlib.Path(filepath)
if (not file.exists()):
print("'{}', no file found".format(filepath))
return
print("File: {}, Contact: {}".format(filepath, contact))
# Is contact online?
if (contact not in getOnlineContacts()):
print("Contact '{}' is not online".format(contact))
return
# ######################## HELPERS ######################## #
def getOnlineContacts():
peerlist = list()
for peer in peerDetect.getPeerList():
if (doesContactExist(peer)):
peerlist.append(getContact(peer)['name'])
return peerlist
def doesContactExist(name):
config = readConfig()
try:
if (config['Contacts ' + name]):
return True
except KeyError:
return False
def getContact(name):
config = readConfig()
return config['Contacts ' + name]
# Find if a user is already registered
# Done by checking the config file and seeing if it contains credentials
def isRegistered():
config = readConfig()
# Ask for forgiveness not permission
# ? Only checks for the existence of credentials not the validity
# ? of credentials, is this good enough?
try:
config['Cred']['name']
config['Cred']['email']
config['Cred']['password']
config['Cred']['private_key']
config['Cred']['public_key']
return True
except KeyError: # Key does not exist in file
return False
# Prompt the user for registration credentials, save to config if valid
def register():
print('Register')
name = input('Enter your full name: ')
email = input('Enter your email address: ')
raw_password = getpass.getpass('Enter your password: ')
password = cryptPassword(raw_password)
if (not checkPassword(getpass.getpass('Re-enter your password: '),
password)):
exit('Password Mismatch, Registration cancelled')
# Generate RSA Public/Private Key
key = RSA.generate(2048)
private_key = key.export_key(passphrase=raw_password, pkcs=8,
protection='scryptAndAES128-CBC')
public_key = key.publickey().export_key()
del raw_password
print('Registration Successful')
# Save credentials to config
config = readConfig()
config['Cred'] = {
'name': name,
'email': email,
'password': password,
'public_key': public_key,
'private_key': private_key}
writeConfig(config)
def login():
print('login')
# ! Should not tell the user which part of the credential is invalid
# ! Need to save some information generated from the password to use to
# ! during the application run
enteredEmail = input('Enter your email address: ')
config = readConfig()
email = config['Cred']['email']
rawPassword = str
if (email == enteredEmail):
password = config['Cred']['password']
rawPassword = getpass.getpass('Enter your password: ')
if (not checkPassword(rawPassword, password)):
exit('Password Mismatch, Login cancelled')
else:
exit('User is not registered, Login cancelled')
# If above checks pass, user is valid
# Save login information to use in crypto functions
UserName = config['Cred']['name']
Email = config['Cred']['email']
peerDetect.id = abs(hash(UserName+Email))
peerDetect.name = UserName
peerDetect.setDebug(DEBUG)
peerDetect.start()
startloop()
# key = RSA.import_key(config['Cred']['private_key'], passphrase=rawPassword)
def checkPassword(plaintext, crypt):
return comp_hash(cryptPasswordSalted(plaintext, crypt), crypt)
def cryptPassword(plaintext):
# Crypt will always use strongest salt available
return crypt.crypt(plaintext)
def cryptPasswordSalted(plaintext, salt):
return crypt.crypt(plaintext, salt)
def readConfig():
config = configparser.ConfigParser()
if (CONFIGFILE.exists()):
with open(CONFIGFILE, "r+") as fp:
config.read_file(fp)
return config
def writeConfig(config):
with open(CONFIGFILE, "w+") as fp:
config.write(fp)
# ######################## PeerDetect Setup ######################## #
timeloop = Timeloop()
timeloopLogger = logging.getLogger('timeloop')
timeloopLogger.propagate = False
timeloopLogger.setLevel(logging.CRITICAL)
peerDetect = PeerDetect()
# Async function for broadcasting alive to peers
@timeloop.job(interval=timedelta(seconds=10))
def broadcast():
s = StringPacket.build(dict(id=peerDetect.id, name=peerDetect.name,
confin=dict(key=4, secret=6)))
peerDetect.send(message=s)
# Async function for receiving messages from peers
@timeloop.job(interval=timedelta(seconds=1))
def receive():
peerDetect.updateMessages()
# Utility to start non blocking timeloop
def startloop():
timeloop.start(block=False)
# Utility to stop timeloop
def stoploop():
timeloop.stop()
# Clean exit of subshell
def cleanUpAndExit():
print('Exit SecureDrop')
exit(0)
# Check to see if we are in a module or the main application
# If main, run main
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print('Force closing the application due to SIG')