You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Comrad/komrade/backend/the_operator.py

574 lines
20 KiB
Python

4 years ago
"""
There is only one operator!
Running on node prime.
"""
# internal imports
import os,sys; sys.path.append(os.path.abspath(os.path.join(os.path.abspath(os.path.join(os.path.dirname(__file__),'..')),'..')))
from komrade import *
4 years ago
from komrade.backend import *
4 years ago
from komrade.backend.messages import Message
4 years ago
# print(PATH_OPERATOR_WEB_KEYS_URL)
4 years ago
# def TheOperator(*x,**y):
# from komrade.backend.operators import Komrade
# return Komrade(OPERATOR_NAME,*x,**y)
4 years ago
OP_PRIVKEY = None
4 years ago
class TheOperator(Operator):
"""
4 years ago
The remote operator
4 years ago
"""
4 years ago
@property
def phone(self):
4 years ago
global TELEPHONE
4 years ago
from komrade.backend.the_telephone import TheTelephone
4 years ago
if not TELEPHONE: TELEPHONE=TheTelephone()
4 years ago
return TELEPHONE
4 years ago
4 years ago
def __init__(self, name = OPERATOR_NAME, passphrase=None):
4 years ago
"""
Boot up the operator. Requires knowing or setting a password of memory.
"""
4 years ago
global OP_PRIVKEY
4 years ago
super().__init__(
name,
path_crypt_keys=PATH_CRYPT_OP_KEYS,
4 years ago
path_crypt_data=PATH_CRYPT_OP_DATA
)
4 years ago
from komrade.backend.phonelines import check_phonelines
keychain = check_phonelines()[OPERATOR_NAME]
4 years ago
self._keychain = {**self.load_keychain_from_bytes(keychain)}
4 years ago
4 years ago
if not keychain.get('pubkey'):
4 years ago
raise KomradeException('Operator cannot find its own public key? Shutting down.')
4 years ago
# check I match what's on op page
pub_web = komrade_request(PATH_OPERATOR_WEB_KEYS_URL)
4 years ago
if pub_web.status_code!=200:
raise KomradeException("Can't verify Komrade Operator. Shutting down.")
4 years ago
# print('Public key on komrade.app/pub: ',pub_web.text)
# print('Public key hardcoded in client: ',keychain.get('pubkey').data_b64_s)
4 years ago
if pub_web.text == keychain.get('pubkey').data_b64_s:
# print('Pubs match')
pass
4 years ago
else:
raise KomradeException('Public key for Operator on app and one at {PATH_OPERATOR_WEB_KEYS_URL} do not match. Shutting down.')
4 years ago
privkey=None
if os.path.exists(PATH_SUPER_SECRET_OP_KEY):
4 years ago
if OP_PRIVKEY:
privkey=OP_PRIVKEY
else:
print('Dare I claim to be the one true Operator?')
with open(PATH_SUPER_SECRET_OP_KEY,'rb') as f:
4 years ago
#pass_encr=f.read()
privkey = f.read()
# try:
# privkey=KomradeSymmetricKeyWithPassphrase().decrypt(pass_encr)
# if privkey: OP_PRIVKEY = privkey
# except ThemisError:
# exit('invalid password. operator shutting down.')
4 years ago
if privkey:
4 years ago
self._keychain['privkey']=KomradeAsymmetricPrivateKey(b64dec(privkey))
4 years ago
# print(self._keychain['privkey'],'??')
4 years ago
self._keychain = {**self.keychain()}
4 years ago
# self.log('@Operator booted with keychain:',dict_format(self._keychain),'and passphrase',self.passphrase)
4 years ago
# clear_screen()
4 years ago
4 years ago
4 years ago
4 years ago
def ring(self,
4 years ago
from_caller=None,
to_caller=None,
json_phone2phone={},
json_caller2phone={}, # (person) -> operator or operator -> (person)
json_caller2caller={}):
4 years ago
encr_msg_to_send = super().ring(
4 years ago
from_phone=self,
to_phone=self.phone,
from_caller=from_caller,
to_caller=to_caller,
json_phone2phone=json_phone2phone,
json_caller2phone=json_caller2phone, # (person) -> operator
json_caller2caller=json_caller2caller)
return self.send(encr_msg_to_send)
4 years ago
# ends the ring_ring() chain
4 years ago
def answer_phone(self,data_b):
4 years ago
# route incoming call from the switchboard
4 years ago
from komrade.cli.artcode import ART_OLDPHONE4
4 years ago
4 years ago
4 years ago
self.log(f'''Hello, this is the Operator.{ART_OLDPHONE4}I heard you say:\n\n {b64enc_s(data_b)}''')
4 years ago
#woops
4 years ago
# unseal
4 years ago
# self.log('got:',data_b)
4 years ago
msg_d = {
4 years ago
'msg':data_b,
4 years ago
'from_name':self.phone.name,
4 years ago
'from':self.phone.pubkey.data,
'to_name':self.name,
'to':self.pubkey.data,
4 years ago
}
# msg_d = pickle.loads(data_b)
4 years ago
# self.log('msg_d',msg_d)
4 years ago
msg_obj = Message(msg_d)
4 years ago
4 years ago
self.log(f'Decoding the binary, I discovered an encrypted message from {self.phone}\n: {msg_obj}')
4 years ago
4 years ago
# decrypt?
msg_obj.decrypt()
4 years ago
# carry out message instructions
4 years ago
resp_msg_obj = self.route_msg(msg_obj,reencrypt=True) #,route=msg_obj.route)
4 years ago
self.log('Response from message routing:',resp_msg_obj)
4 years ago
# send back down encrypted
4 years ago
# self.log('route msgd',dict_format(resp_msg_obj.msg_d))
# self.log('route msg',resp_msg_obj.msg)
4 years ago
# self.log('route msg data',resp_msg_obj.data)
4 years ago
# self.log('route msg obj',resp_msg_obj)
4 years ago
4 years ago
4 years ago
msg_sealed = pickle.dumps(resp_msg_obj.msg_d)
4 years ago
# self.log('msg_sealed =',msg_sealed)
4 years ago
# return back to phone and back down to chain
return msg_sealed
4 years ago
def has_user(self,name=None,pubkey=None):
4 years ago
nm,pk = name,pubkey
if pubkey: pk=self.crypt_keys.get(
4 years ago
name,
prefix='/pubkey/'
)
4 years ago
if name: nm=self.crypt_keys.get(
4 years ago
b64enc(pubkey),
prefix='/name/'
)
4 years ago
self.log(f'checking whether I have user {name} and {pubkey},\n I discovered I had {nm} and {pk} on record')
4 years ago
# self.log('pks:',pubkey,pk)
# self.log('nms:',name,nm)
4 years ago
return (pubkey and pk) or (name and nm)
4 years ago
def send(self,encr_data_b):
self.log(type(encr_data_b),encr_data_b,'sending!')
return encr_data_b
### ROUTES
4 years ago
def does_username_exist(self,msg_obj):
data=msg_obj.data
name=data.get('name')
pubkey=self.crypt_keys.get(name,prefix='/pubkey/')
self.log(f'looking for {name}, found {pubkey} as pubkey')
return bool(pubkey)
def login(self,msg_obj):
data=msg_obj.data
name=data.get('name')
pubkey=data.get('pubkey')
secret_login=data.get('secret_login')
4 years ago
name=name.encode() if type(name)==str else name
pubkey=pubkey.encode() if type(pubkey)==str else pubkey
secret_login=secret_login.encode() if type(secret_login)==str else secret_login
4 years ago
# get my records
4 years ago
uri = b64enc(pubkey)
4 years ago
name_record = self.crypt_keys.get(
4 years ago
uri,
4 years ago
prefix='/name/'
4 years ago
)
4 years ago
pubkey_record = b64enc(self.crypt_keys.get(
4 years ago
name,
prefix='/pubkey/'
4 years ago
))
secret_record = b64enc(self.crypt_keys.get(
4 years ago
uri,
4 years ago
prefix='/secret_login/'
4 years ago
))
4 years ago
self.log(f'''Checking inputs:
{name} (input)
vs.
4 years ago
{name_record} (record)
4 years ago
4 years ago
{uri} (input)
4 years ago
vs.
4 years ago
{pubkey_record} (record)
4 years ago
4 years ago
{secret_login} (input)
4 years ago
vs.
4 years ago
{secret_record} (record)
4 years ago
''')
4 years ago
# stop
# check name?
4 years ago
if name != name_record:
4 years ago
self.log('names did not match!')
success = False
4 years ago
# # check pubkey?
4 years ago
elif uri != pubkey_record:
self.log('pubkeys did not match!',uri,pubkey_record)
success = False
elif secret_login != secret_record:
self.log('secrets did not match!')
success = False
else:
success = True
## return res
if success:
return {
'success': True,
4 years ago
'status':f'Welcome back, Komrade @{name.decode()}.'
4 years ago
}
else:
return {
'success': False,
'status':'Login failed.'
}
4 years ago
def register_new_user(self,msg_obj):
4 years ago
# self.log('setting pubkey under name')
data=msg_obj.data
name=data.get('name')
pubkey=data.get('pubkey')
4 years ago
# is user already there?
if self.has_user(name=name,pubkey=pubkey):
return {
'success':False,
4 years ago
'status': f"{OPERATOR_INTRO}I'm sorry, but I can't register the name of {name}. This user already exists."
4 years ago
}
4 years ago
4 years ago
# generate shared secret
4 years ago
shared_secret = get_random_binary_id()
4 years ago
self.log(f'{self}: Generated shared secret between {name} and me:\n\n{make_key_discreet(shared_secret)}')
4 years ago
# ok then set what we need
4 years ago
uri_id = b64enc(pubkey)
4 years ago
pubkey_b = b64dec(pubkey)
4 years ago
r1=self.crypt_keys.set(name,pubkey_b,prefix='/pubkey/')
r2=self.crypt_keys.set(uri_id,name,prefix='/name/')
4 years ago
# hide secret as key
4 years ago
r3=self.crypt_keys.set(uri_id,shared_secret,prefix='/secret_login/')
4 years ago
# success?
success = r1 and r2 and r3
if not success:
return {
'success':False,
'status': f"{OPERATOR_INTRO}I'm sorry, but I can't register the name of {name}."
}
4 years ago
# compose result
4 years ago
res = {
'success':success,
4 years ago
'pubkey':pubkey_b,
4 years ago
'secret_login':shared_secret,
4 years ago
'name':name,
}
4 years ago
# res_safe = {
# **res,
# **{
# 'secret_login':make_key_discreet(
# res['secret_login']
# )
# }
# }
4 years ago
# return
4 years ago
self.log('Operator returning result:',dict_format(res,tab=4))
4 years ago
return res
4 years ago
4 years ago
4 years ago
## success msg
4 years ago
#
4 years ago
# cvb64=cv_b64#b64encode(cv).decode()
# qrstr=self.qr_str(cvb64)
# res['status']=self.status(f'''{OPERATOR_INTRO}I have successfully registered Komrade {name}.
4 years ago
4 years ago
# If you're interested, here's what I did. I stored the public key you gave me, {cvb64}, under the name of "{name}". However, I never save that name directly, but record it only in a disguised, "hashed" form: {ck}. I scrambled "{name}" by running it through a 1-way hashing function, which will always yield the same result: provided you know which function I'm using, and what the secret "salt" is that I add to all the input, a string of text which I keep protected and encrypted on my local hard drive.
4 years ago
4 years ago
# The content of your data will therefore not only be encrypted, but its location in my database is obscured even to me. There's no way for me to reverse-engineer the name of {name} from the record I stored it under, {ck}. Unless you explictly ask me for the public key of {name}, I will have no way of accessing that information.
4 years ago
4 years ago
# Your name ({name}) and your public key ({cvb64}) are the first two pieces of information you've given me about yourself. Your public key is your 'address' in Komrade: in order for anyone to write to you, or for them to receive messages from you, they'll need to know your public key (and vise versa). The Komrade app should store your public key on your device as a QR code, under ~/.komrade/.contacts/{name}.png. It will look something like this:{qrstr}You can then send this image to anyone by a secure channel (Signal, IRL, etc), or tell them the code directly ({cvb64}).
4 years ago
4 years ago
# By default, if anyone asks me what your public key is, I won't tell them--though I won't be able to avoid hinting that a user exists under this name should someone try to register under that name and I deny them). Instead, if the person who requested your public key insists, I will send you a message (encrypted end-to-end so only you can read it) that the user who met someone would like to introduce themselves to you; I will then send you their name and public key. It's now your move: up to you whether to save them back your public key.
4 years ago
4 years ago
# If you'd like to change this default behavior, e.g. by instead allowing anyone to request your public key, except for those whom you explcitly block, I have also created a super secret administrative record for you to change various settings on your account. This is protected by a separate encryption key which I have generated for you; and this key which is itself encrypted with the password you entered earlier. Don't worry: I never saw that password you typed, since it was given to me already hashed and disguised. Without that hashed passphrase, no one will be able to unlock the administration key; and without the administration key, they won't be able to find the hashed record I stored your user settings under, since I also salted that hash with your own hashed passphrase. Even if someone found the record I stored them under, they wouldn't be able to decrypt the existing settings; and if they can't do that, I won't let them overwrite the record.''')
4 years ago
4 years ago
# self.log('Operator returning result:',dict_format(res,tab=2))
def deliver_msg(self,msg_to_op):
data = msg_to_op.data
deliver_to = data.get('deliver_to')
deliver_from = data.get('deliver_from')
deliver_msg = data.get('deliver_msg')
if not deliver_to or not deliver_from or not deliver_msg:
4 years ago
return {'success':False, 'status':'Invalid input.'}
if b64enc(deliver_from) != b64enc(data['from']):
return {'success':False, 'status':'Sender to me is not the sender of the message I am to forward'}
to_komrade = Komrade(pubkey=deliver_to)
from_komrade = Komrade(pubkey=deliver_from)
4 years ago
deliver_to_b = b64dec(deliver_to)
4 years ago
self.log(f'''Got:
data = {data}
deliver_to = {deliver_to}
deliver_from = {deliver_from}
deliver_msg = {deliver_msg}
to_komrade = {to_komrade}
from_komrade = {from_komrade}
4 years ago
''')
4 years ago
## just deliver?
4 years ago
4 years ago
from komrade.backend.messages import Message
4 years ago
msg_from_op = Message(
4 years ago
from_whom=self,
msg_d = {
4 years ago
'to':data.get('deliver_to'),
'to_name':data.get('deliver_to_name'),
4 years ago
'msg':{
4 years ago
'to':data.get('deliver_to'),
'to_name':data.get('deliver_to_name'),
'from':data.get('deliver_from'),
'from_name':data.get('deliver_from_name'),
'msg':data.get('deliver_msg'),
},
'note':'Someone (marked "from") would like to send you (marked "to") this message (marked "msg").'
4 years ago
}
4 years ago
)
4 years ago
self.log(f'{self}: Prepared this msg for delivery:\n{msg_from_op}')
4 years ago
4 years ago
# encrypt
msg_from_op.encrypt()
4 years ago
return self.actually_deliver_msg(msg_from_op)
4 years ago
def actually_deliver_msg(self,msg_from_op):
4 years ago
msg_from_op_b_encr = msg_from_op.msg #.msg_b # pickle of msg_d
4 years ago
self.log('got this:',msg_from_op_b_encr)
4 years ago
deliver_to = msg_from_op.to_pubkey
deliver_to_b = b64dec(deliver_to)
4 years ago
4 years ago
# save new post
post_id = get_random_binary_id()
4 years ago
self.crypt_keys.set(
post_id,
msg_from_op_b_encr,
prefix='/post/'
)
4 years ago
4 years ago
# get inbox
4 years ago
inbox_old_encr = self.crypt_keys.get(deliver_to,prefix='/inbox/')
4 years ago
if inbox_old_encr:
4 years ago
inbox_old = SMessage(
self.privkey.data,
deliver_to_b
).unwrap(inbox_old_encr) #.split(BSEP)
4 years ago
else:
4 years ago
inbox_old=b''
self.log('reloaded inbox:',inbox_old)
4 years ago
4 years ago
# add new inbox
4 years ago
inbox_new = post_id + (BSEP+inbox_old if inbox_old else b'')
4 years ago
self.log('new inbox = ',inbox_new)
4 years ago
# reencrypt
inbox_new_encr = SMessage(
self.privkey.data,
deliver_to_b
).wrap(inbox_new)
4 years ago
# encrypt
self.log('new inbox encr:',inbox_new_encr)
# save back to crypt
4 years ago
self.crypt_keys.set(
deliver_to,
inbox_new_encr,
prefix='/inbox/',
override=True
)
4 years ago
4 years ago
return {
'status':'Message delivered.',
'success':True,
'post_id':post_id
}
4 years ago
def check_msgs(self,
4 years ago
msg_to_op,
required_fields = [
'secret_login',
'name',
'pubkey',
'inbox',
]):
# logged in?
login_res = self.login(msg_to_op)
if not login_res.get('success'):
return login_res
# ok, then find the inbox?
inbox=msg_to_op.data.get('inbox')
if not inbox: inbox=msg_to_op.data.get('pubkey')
if not inbox: return {'success':False, 'status':'No inbox specified'}
inbox_encr = self.crypt_keys.get(b64enc(inbox),prefix='/inbox/')
# fine: here, try this on for size
4 years ago
return {
'status':'Succeeded in getting inbox.',
'success':True,
'data_encr':inbox_encr
}
4 years ago
4 years ago
def download_msgs(self,
4 years ago
msg_to_op,
required_fields = [
'secret_login',
'name',
'pubkey',
'post_ids',
4 years ago
],
delete_afterward=True):
4 years ago
# logged in?
login_res = self.login(msg_to_op)
if not login_res.get('success'):
return login_res
# ok, then find the posts?
post_ids=msg_to_op.data.get('post_ids',[])
if not post_ids: return {'success':False, 'status':'No post_ids specified'}
posts = {}
for post_id in post_ids:
post = self.crypt_keys.get(b64enc(post_id),prefix='/post/')
if post:
posts[post_id] = post
self.log(f'I {self} found {len(posts)} for {msg_to_op.from_name}')
4 years ago
# delete?
if delete_afterward:
# @hack: this a bit dangerous?
for post_id in posts:
self.crypt_keys.delete(
post_id,
prefix='/post/'
)
self.log('deleting post id',post_id,'...')
4 years ago
return {
4 years ago
'status':'Succeeded in downloading new messages.' + (' I\'ve already deleted these messages from the server.' if delete_afterward else ''),
4 years ago
'success':True,
'data_encr':posts
}
4 years ago
4 years ago
def introduce_komrades(self,msg_to_op):
4 years ago
# logged in?
login_res = self.login(msg_to_op)
if not login_res.get('success'):
return login_res
4 years ago
data=msg_to_op.data
4 years ago
self.log('Op sees data:',dict_format(data))
4 years ago
4 years ago
meet_pubkey = self.crypt_keys.get(
data.get('meet_name'),
'/pubkey/'
)
4 years ago
self.log('found in crypt:',meet_pubkey)
4 years ago
4 years ago
msg = Message(
{
4 years ago
'to':meet_pubkey,
4 years ago
'to_name':data.get('meet_name'),
4 years ago
'from':self.uri,
4 years ago
'from_name':self.name,
'msg': {
'type':'introdution',
4 years ago
'status':f'''Komrade {data.get("name")} would like to make your acquaintance. Their public key is {data.get("pubkey")}.''',
4 years ago
'meet_name': data.get('name'),
'meet_pubkey': data.get('pubkey')
}
}
)
4 years ago
msg.encrypt()
# self.log('formed msg:',msg.msg_d)
4 years ago
return self.actually_deliver_msg(msg)
4 years ago
def test_op():
4 years ago
from komrade.backend.the_telephone import TheTelephone
4 years ago
from getpass import getpass
4 years ago
op = TheOperator()
4 years ago
# op.boot()
4 years ago
keychain_op = op.keychain()
4 years ago
4 years ago
4 years ago
phone = TheTelephone()
# phone.boot()
4 years ago
keychain_ph = phone.keychain()
4 years ago
4 years ago
from pprint import pprint
4 years ago
print('REASSEMBLED OPERATOR KEYCHAIN')
pprint(keychain_op)
# stop
4 years ago
print('REASSEMBLED TELEPHONE KEYCHAIN')
4 years ago
pprint(keychain_ph)
4 years ago
4 years ago
# print(op.pubkey(keychain=keychain))
4 years ago
# print(op.crypt_keys.get(op.pubkey(), prefix='/privkey_encr/'))
4 years ago
# print(op.crypt_keys.get(op.name, prefix='/pubkey_encr/'))
4 years ago
# print(op.pubkey_)
4 years ago
4 years ago
4 years ago
# stop
4 years ago
4 years ago
# pubkey = op.keychain()['pubkey']
# pubkey_b64 = b64encode(pubkey)
# print(pubkey)
4 years ago
if __name__ == '__main__': test_op()