├── tests ├── __init__.py ├── test_utils.py ├── test_states.py ├── conftest.py ├── utils.py ├── test_db.py └── test_conversations.py ├── .gitattributes ├── .gitignore ├── setup.cfg ├── MANIFEST.in ├── utilities ├── README.md ├── encrypt_decrypt_file.py ├── convert_dbs.py ├── gen_database_pair.py └── init_conversation.py ├── examples ├── name1.py ├── name2.py ├── create_states.py ├── README.md ├── wh.py ├── ratchet_watcher.py ├── transfer.py ├── axochat.py ├── smp.py └── axotor.py ├── setup.py ├── README.rst ├── _version.py ├── pyaxo.py └── COPYING /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | _version.py export-subst 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | tests/axolotl.db 3 | .idea/ 4 | build/ 5 | dist/ 6 | pyaxo.egg-info/ 7 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [versioneer] 2 | VCS = git 3 | versionfile_source = _version.py 4 | versionfile_build = 5 | tag_prefix = 6 | parentdir_prefix = 7 | 8 | [aliases] 9 | test=pytest 10 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include COPYING 2 | include README.rst 3 | include _version.py 4 | include versioneer.py 5 | recursive-include examples * 6 | recursive-include tests * 7 | recursive-include utilities * 8 | -------------------------------------------------------------------------------- /utilities/README.md: -------------------------------------------------------------------------------- 1 | #### Utilities for using pyaxo... 2 | 3 | This utility will create a conversation in the database: 4 | 5 | init_conversation.py 6 | 7 | This utility will encrypt or decrypt a file: 8 | 9 | encrypt_decrypt_file.py 10 | -------------------------------------------------------------------------------- /examples/name1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from pyaxo import Axolotl 4 | import sys 5 | 6 | a = Axolotl('name1', dbname='name1.db', dbpassphrase=None) 7 | a.loadState('name1', 'name2') 8 | 9 | if sys.argv[1] == '-e': 10 | a.encrypt_file(sys.argv[2]) 11 | print 'Encrypted file is ' + sys.argv[2] +'.asc' 12 | else: 13 | a.decrypt_file(sys.argv[2]) 14 | 15 | a.saveState() 16 | 17 | -------------------------------------------------------------------------------- /examples/name2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from pyaxo import Axolotl 4 | import sys 5 | 6 | a = Axolotl('name2', dbname='name2.db', dbpassphrase=None) 7 | a.loadState('name2', 'name1') 8 | 9 | if sys.argv[1] == '-e': 10 | a.encrypt_file(sys.argv[2]) 11 | print 'Encrypted file is ' + sys.argv[2] +'.asc' 12 | else: 13 | a.decrypt_file(sys.argv[2]) 14 | 15 | a.saveState() 16 | 17 | -------------------------------------------------------------------------------- /tests/test_utils.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from pyaxo import generate_keypair 4 | 5 | 6 | @pytest.fixture() 7 | def keypair(): 8 | return generate_keypair() 9 | 10 | 11 | def test_keypair_tuple(keypair): 12 | assert isinstance(keypair, tuple) 13 | assert keypair.priv == keypair[0] and keypair.pub == keypair[1] 14 | 15 | 16 | def test_keypair_different_values(keypair): 17 | assert keypair.priv != keypair.pub 18 | 19 | 20 | def test_keypair_bytes(keypair): 21 | assert isinstance(keypair.priv, bytes) and isinstance(keypair.pub, bytes) 22 | -------------------------------------------------------------------------------- /examples/create_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from pyaxo import Axolotl 4 | import sys 5 | import os 6 | 7 | # start with a fresh database 8 | try: 9 | os.remove('./name1.db') 10 | os.remove('./name2.db') 11 | except OSError: 12 | pass 13 | 14 | # unencrypted databases 15 | a = Axolotl('name1', dbname='name1.db', dbpassphrase=None) 16 | b = Axolotl('name2', dbname='name2.db', dbpassphrase=None) 17 | 18 | a.initState('name2', b.state['DHIs'], b.handshakePKey, b.state['DHRs'], verify=False) 19 | b.initState('name1', a.state['DHIs'], a.handshakePKey, a.state['DHRs'], verify=False) 20 | 21 | a.saveState() 22 | b.saveState() 23 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | try: 2 | from setuptools import setup 3 | except ImportError: 4 | from distutils.core import setup 5 | 6 | import versioneer 7 | 8 | 9 | setup( 10 | name='pyaxo', 11 | version=versioneer.get_version(), 12 | cmdclass=versioneer.get_cmdclass(), 13 | description='Python implementation of the Axolotl ratchet protocol', 14 | author='David R. Andersen', 15 | author_email='k0rx@RXcomm.net', 16 | url='https://github.com/rxcomm/pyaxo', 17 | py_modules=[ 18 | 'pyaxo' 19 | ], 20 | install_requires=[ 21 | 'passlib>=1.6.1', 22 | 'pynacl>=1.0.1', 23 | ], 24 | setup_requires=[ 25 | 'pytest-runner', 26 | ], 27 | tests_require=[ 28 | 'pytest', 29 | ], 30 | ) 31 | -------------------------------------------------------------------------------- /tests/test_states.py: -------------------------------------------------------------------------------- 1 | def test_init_state(axolotl_a, axolotl_b, exchange): 2 | axolotl_a.initState(other_name=axolotl_b.name, 3 | other_identityKey=axolotl_b.state['DHIs'], 4 | other_handshakeKey=axolotl_b.handshakePKey, 5 | other_ratchetKey=axolotl_b.state['DHRs'], 6 | verify=False) 7 | 8 | axolotl_b.initState(other_name=axolotl_a.name, 9 | other_identityKey=axolotl_a.state['DHIs'], 10 | other_handshakeKey=axolotl_a.handshakePKey, 11 | other_ratchetKey=axolotl_a.state['DHRs'], 12 | verify=False) 13 | 14 | exchange(axolotl_a, axolotl_b) 15 | 16 | 17 | def test_create_state(axolotl_a, axolotl_b, exchange): 18 | mkey = 'masterkey' 19 | 20 | axolotl_a.createState(other_name=axolotl_b.name, 21 | mkey=mkey, 22 | mode=True, 23 | other_ratchetKey=axolotl_b.state['DHRs']) 24 | axolotl_b.createState(other_name=axolotl_a.name, 25 | mkey=mkey, 26 | mode=False) 27 | 28 | exchange(axolotl_a, axolotl_b) 29 | -------------------------------------------------------------------------------- /utilities/encrypt_decrypt_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | This program will encrypt or decrypt a file 5 | """ 6 | 7 | from pyaxo import Axolotl 8 | import sys 9 | 10 | your_name = raw_input('What is your name? ').strip() 11 | 12 | # specify dbname with kwarg - default dbname is axolotl.db 13 | # db passphrase will be prompted for - it can be specified here with dbpassprase kwarg 14 | a = Axolotl(your_name, dbname=your_name+'.db') 15 | 16 | try: 17 | if sys.argv[1] == '-e': 18 | other_name = \ 19 | raw_input("What is the name of the party that you want to encrypt the file to? " ).strip() 20 | a.loadState(your_name, other_name) 21 | a.encrypt_file(sys.argv[2]) 22 | print 'The encrypted file is: ' + sys.argv[2] + '.asc' 23 | else: 24 | other_name = \ 25 | raw_input("What is the name of the party that you want to decrypt the file from? " ).strip() 26 | a.loadState(your_name, other_name) 27 | a.decrypt_file(sys.argv[2]) 28 | except IndexError: 29 | print 'Usage: ' + sys.argv[0] + ' -(e,d) ' 30 | exit() 31 | except KeyError: 32 | print 'The conversation ' + your_name + ' -> ' + other_name + \ 33 | ' is not in the database' 34 | exit() 35 | 36 | a.saveState() 37 | 38 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from pyaxo import Axolotl, generate_keypair 4 | 5 | from . import utils 6 | 7 | 8 | @pytest.fixture() 9 | def a_identity_keys(): 10 | return generate_keypair() 11 | 12 | 13 | @pytest.fixture() 14 | def b_identity_keys(): 15 | return generate_keypair() 16 | 17 | 18 | @pytest.fixture() 19 | def c_identity_keys(): 20 | return generate_keypair() 21 | 22 | 23 | @pytest.fixture() 24 | def a_handshake_keys(): 25 | return generate_keypair() 26 | 27 | 28 | @pytest.fixture() 29 | def b_handshake_keys(): 30 | return generate_keypair() 31 | 32 | 33 | @pytest.fixture() 34 | def c_handshake_keys(): 35 | return generate_keypair() 36 | 37 | 38 | @pytest.fixture() 39 | def a_ratchet_keys(): 40 | return generate_keypair() 41 | 42 | 43 | @pytest.fixture() 44 | def b_ratchet_keys(): 45 | return generate_keypair() 46 | 47 | 48 | @pytest.fixture() 49 | def c_ratchet_keys(): 50 | return generate_keypair() 51 | 52 | 53 | @pytest.fixture() 54 | def axolotl_a(): 55 | return Axolotl('Angie', dbpassphrase=None) 56 | 57 | 58 | @pytest.fixture() 59 | def axolotl_b(): 60 | return Axolotl('Barb', dbpassphrase=None) 61 | 62 | 63 | @pytest.fixture() 64 | def axolotl_c(): 65 | return Axolotl('Charlie', dbpassphrase=None) 66 | 67 | 68 | @pytest.fixture(params=utils.EXCHANGES, ids=utils.EXCHANGE_IDS) 69 | def exchange(request): 70 | return request.param 71 | -------------------------------------------------------------------------------- /utilities/convert_dbs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | This script is used to convert encrypted Axolotl's database files created with 4 | pyaxo < 0.6.0 into files created with pyaxo >= 0.6.0, which replaced GPG by 5 | PyNaCl for encryption. 6 | 7 | To convert the databases, add each filename to the `DATABASE_NAMES` list and 8 | run the script. It will prompt for each file's passphrase, decrypt with the 9 | previously used cipher and encrypt with the current one. If the databases share 10 | the same passphrase, the `dbpassphrase` declaration can be moved out of the 11 | loop so that it will be prompted only once. 12 | """ 13 | import gnupg 14 | import sys 15 | from getpass import getpass 16 | 17 | from pyaxo import encrypt_symmetric, hash_ 18 | 19 | 20 | DATABASE_NAMES = [] 21 | 22 | 23 | def convert_dbs(): 24 | gpg = gnupg.GPG() 25 | gpg.encoding = 'utf-8' 26 | 27 | for dbname in DATABASE_NAMES: 28 | with open(dbname, 'rb') as f: 29 | dbpassphrase = getpass('Type passphrase for "{}": '.format(dbname)) 30 | sql = gpg.decrypt_file(f, passphrase=dbpassphrase).data 31 | 32 | if sql: 33 | with open(dbname, 'wb') as f: 34 | new_crypt_sql = encrypt_symmetric(key=hash_(dbpassphrase), 35 | plaintext=sql) 36 | f.write(new_crypt_sql) 37 | else: 38 | print 'Bad passphrase!' 39 | 40 | 41 | if __name__ == '__main__': 42 | sys.exit(convert_dbs()) 43 | -------------------------------------------------------------------------------- /utilities/gen_database_pair.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | This script will generate a pair of databases named after two conversants. 5 | The databases can then be securely distributed to initialize axolotl. 6 | 7 | You will need to provide your name and the other party's name. Conversations 8 | are identified by your name and the other person's name. The conversation 9 | should have a unique other person's name. 10 | 11 | If you decide not to complete the initialization process, just answer no to the 12 | question about creating a new conversation. Nothing will be saved. 13 | 14 | If you want to reinitialize a conversation, just run the script again. 15 | The old conversation key data will be overwritten in the databases. 16 | """ 17 | 18 | import sys 19 | import binascii 20 | from pyaxo import Axolotl 21 | 22 | your_name = raw_input('Your name for this conversation? ').strip() 23 | other_name = raw_input('What is the name of the other party? ').strip() 24 | a = Axolotl(your_name,dbname=your_name+'.db') 25 | b = Axolotl(other_name,dbname=other_name+'.db') 26 | a.initState(other_name, b.state['DHIs'], b.handshakePKey, b.state['DHRs'], verify=False) 27 | b.initState(your_name, a.state['DHIs'], a.handshakePKey, a.state['DHRs'], verify=False) 28 | 29 | a.saveState() 30 | b.saveState() 31 | print 'The conversation ' + your_name + ' -> ' + other_name + ' has been saved in: ' + your_name + '.db' 32 | print 'The conversation ' + other_name + ' -> ' + your_name + ' has been saved in: ' + other_name + '.db' 33 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | Here is a toy example that you can run to see how the Axolotl ratchet works. 2 | 3 | First, create the database by running 4 | 5 | ./create_states.py 6 | 7 | This will set up two databases - one for each of the name1 and name2 identities. 8 | The databases will be unencrypted. You can set a passphrase with the 9 | dbpassphrase kwarg, or leave it out to have the system prompt for a passphrase. 10 | 11 | Then create several text files to encrypt. Encrypt a file from name1 -> name2 12 | using the following command: 13 | 14 | ./name1.py -e 15 | 16 | You can then decrypt the file using the command: 17 | 18 | ./name2.py -d .asc 19 | 20 | Try encrypting multiple files in both directions. Decrypt them out of order, and try 21 | to cause other mayhem. pyaxo should sort it all out for you. 22 | 23 | I've also added ```ratchet_viewer.py```, a utility that you can use to view 24 | the ratchet state as it changes. After you've initialized the name1/name2 25 | databases, run ```ratchet_viewer.py``` in another window in the same directory. 26 | Load the new state as you encrypt/decrypt files and it will show you the changes. 27 | 28 | One thing you may notice is that you can only decrypt a file once - after that, 29 | because of the perfect forward secrecy provided by Axolotl, the key is __gone__! 30 | 31 | Finally, there is a file transfer example ```transfer.py```, and a standalone chat 32 | program ```axochat.py```. These illustrate the use of a context manager with Axolotl. 33 | -------------------------------------------------------------------------------- /utilities/init_conversation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | This script will add a new conversation between two parties to the 5 | axolotl database. 6 | 7 | You will need to provide the other party's name, identity key, handshake key, 8 | and ratchet key. Conversations are identified by your name and the other person's 9 | name. Each conversation should have a unique other person's name. Your name can be 10 | the same for each conversation or different for each one or any combination. 11 | 12 | If you decide not to complete the initialization process, just answer no to the 13 | question about creating a new conversation. Nothing will be saved. 14 | 15 | If you want to reinitialize a conversation, just run the script again. 16 | The old conversation key data will be overwritten in the database. 17 | """ 18 | 19 | import sys 20 | import binascii 21 | from pyaxo import Axolotl 22 | 23 | your_name = raw_input('Your name for this conversation? ').strip() 24 | a = Axolotl(your_name) 25 | a.printKeys() 26 | 27 | ans = raw_input('Do you want to create a new conversation? y/N ').strip() 28 | if ans == 'y': 29 | other_name = raw_input('What is the name of the other party? ').strip() 30 | identity = raw_input('What is the identity key for the other party? ').strip() 31 | handshake = raw_input('What is the handshake key for the other party? ').strip() 32 | ratchet = raw_input('What is the ratchet key for the other party? ').strip() 33 | a.initState(other_name, binascii.a2b_base64(identity), binascii.a2b_base64(handshake), 34 | binascii.a2b_base64(ratchet)) 35 | a.saveState() 36 | print 'The conversation ' + your_name + ' -> ' + other_name + ' has been saved.' 37 | else: 38 | print 'OK, nothing has been saved...' 39 | 40 | -------------------------------------------------------------------------------- /examples/wh.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2 2 | import os 3 | import hashlib as h 4 | from twisted.internet import reactor 5 | from twisted.internet.defer import inlineCallbacks 6 | from wormhole.cli.public_relay import RENDEZVOUS_RELAY 7 | import wormhole 8 | from wormhole.tor_manager import get_tor 9 | from wormhole.timing import DebugTiming 10 | 11 | class WHMgr(object): 12 | def __init__(self, code, data, tor_port): 13 | self._code = code 14 | self._tor_port = tor_port 15 | self._reactor = reactor 16 | self._timing = DebugTiming() 17 | self.confirmed = False 18 | self.data = data 19 | 20 | @inlineCallbacks 21 | def start_tor(self): 22 | self._tor = yield get_tor(self._reactor, 23 | launch_tor=False, 24 | tor_control_port=self._tor_port, 25 | timing=self._timing) 26 | return 27 | 28 | @inlineCallbacks 29 | def send(self): 30 | """I send data through a wormhole and return True/False 31 | depending on whether or not the hash matched at the receive 32 | side. 33 | """ 34 | def _confirm(input_message): 35 | if input_message == 'Confirmed!': 36 | self.confirmed = True 37 | 38 | yield self.start_tor() 39 | self._w = wormhole.create(u'axotor', RENDEZVOUS_RELAY, self._reactor, 40 | tor=self._tor, timing=self._timing) 41 | self._w.set_code(self._code) 42 | self._w.send_message(self.data+h.sha256(self.data).hexdigest()) 43 | yield self._w.get_message().addCallback(_confirm) 44 | yield self._w.close() 45 | self._reactor.stop() 46 | return 47 | 48 | @inlineCallbacks 49 | def receive(self): 50 | """I receive data+hash, check for a match, confirm or not 51 | confirm to the sender, and return the data payload. 52 | """ 53 | def _receive(input_message): 54 | self.data = input_message[:-64] 55 | _hash = input_message[-64:] 56 | if h.sha256(self.data).hexdigest() == _hash: 57 | self._w.send_message('Confirmed!') 58 | else: 59 | self._w.send_message('Not Confirmed!') 60 | 61 | yield self.start_tor() 62 | self._w = wormhole.create(u'axotor', RENDEZVOUS_RELAY, self._reactor, 63 | tor=self._tor, timing=self._timing) 64 | self._w.set_code(self._code) 65 | yield self._w.get_message().addCallback(_receive) 66 | yield self._w.close() 67 | self._reactor.stop() 68 | return 69 | 70 | def run(self): 71 | self._reactor.run() 72 | -------------------------------------------------------------------------------- /examples/ratchet_watcher.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import copy 4 | import os 5 | from pyaxo import Axolotl 6 | 7 | name1 = 'Angie' 8 | name2 = 'Barb' 9 | 10 | a = Axolotl(name1, dbname='name1.db', dbpassphrase=None) 11 | b = Axolotl(name2, dbname='name2.db', dbpassphrase=None) 12 | 13 | a.loadState(name1, name2) 14 | b.loadState(name2, name1) 15 | 16 | topic = [' My Name', 17 | 'Other Name', 18 | ' RK', 19 | ' HKs', 20 | ' HKr', 21 | ' NHKs', 22 | ' NHKr', 23 | ' CKs', 24 | ' CKr', 25 | ' DHIs_priv', 26 | ' DHIs', 27 | ' DHIr', 28 | ' DHRs_priv', 29 | ' DHRs', 30 | ' DHRr', 31 | ' CONVid', 32 | ' Ns', 33 | ' Nr', 34 | ' PNs', 35 | ' ratchet', 36 | ' mode'] 37 | 38 | def hilite(text, c=False): 39 | attr = [] 40 | if c: 41 | attr.append('41') 42 | return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), text) 43 | 44 | data_old = False 45 | os.system('clear') 46 | while True: 47 | print '\x1b[;32m Name: 1 2\x1b[0m' 48 | print '--------------' 49 | a.loadState(name1, name2) 50 | b.loadState(name2, name1) 51 | databases = (a.db, b.db) 52 | data = [] 53 | a_chg = False 54 | b_chg = False 55 | for number, database in enumerate(databases): 56 | cur = database.cursor() 57 | cur.execute('SELECT * from conversations') 58 | data += [cur.fetchall()] 59 | if not data_old: 60 | data_old = data 61 | for i in range(len(data[0][0])): 62 | if data[0][0][i] != data_old[0][0][i]: a_chg=True 63 | if data[1][0][i] != data_old[1][0][i]: b_chg=True 64 | if topic[i] == ' mode': 65 | if data[0][0][i] == 1: 66 | var = 'A' 67 | var2 = 'B' 68 | else: 69 | var = 'B' 70 | var2 = 'A' 71 | elif topic[i]==' Ns' or topic[i]==' Nr' or topic[i]==' PNs': 72 | var = data[0][0][i] 73 | var2 = data[1][0][i] 74 | elif topic[i] == ' ratchet': 75 | var = 'F' 76 | var2 = 'F' 77 | if data[0][0][i] == 1: 78 | var = 'T' 79 | elif data[1][0][i] == 1: 80 | var2 = 'T' 81 | else: 82 | var = '*' 83 | var2 = '*' 84 | print topic[i], hilite(var, a_chg), hilite(var2, b_chg) 85 | a_chg = False 86 | b_chg = False 87 | print '--------------' 88 | ans = raw_input('Load new state? ') 89 | if ans=='q' or ans=='n': exit() 90 | os.system('clear') 91 | data_old = data 92 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Python implementation of the Double Ratchet Algorithm. 2 | ====================================================== 3 | 4 | Overview 5 | -------- 6 | The Double Ratchet Algorithm is a protocol (similar to OTR) that 7 | provides for perfect forward secrecy in (a)synchronous 8 | communications. It uses triple Diffie-Hellman for 9 | authentication and ECDHE for perfect forward secrecy. 10 | The protocol is lighter and more robust than the OTR 11 | protocol - providing better forward and future secrecy, 12 | as well as deniability. 13 | 14 | The protocol was developed by Trevor Perrin and Moxie 15 | Marlinspike. Its chief use currently is in the Open Whisper Systems 16 | Signal package. 17 | 18 | A nice writeup of the protocol is on the `Open Whisper Systems Blog`_. 19 | You can find the most recent specification of the protocol 20 | `here `_. 21 | 22 | Installation instructions 23 | ------------------------- 24 | Make sure that you have the following:: 25 | 26 | # If using Debian/Ubuntu 27 | sudo apt-get install gcc libffi-dev libsodium-dev python-dev 28 | 29 | # If using Fedora 30 | sudo yum install gcc libffi-devel libsodium-devel python-devel redhat-rpm-config 31 | 32 | pyaxo also uses `pynacl`_ and `passlib`_, 33 | but these packages will be downloaded and installed automatically by 34 | `pip`_/`setuptools`_. 35 | 36 | If you use *pip*, install pyaxo with:: 37 | 38 | sudo pip install pyaxo 39 | 40 | If you use *setuptools*, change to pyaxo's source folder and install 41 | with:: 42 | 43 | sudo python setup.py install 44 | 45 | **pyaxo will be ready for use!** 46 | 47 | If you do not use neither of those, you will have to manually install 48 | each dependency before running the previous command. 49 | 50 | Usage 51 | ----- 52 | There are several examples showing usage. There are also 53 | ``encrypt_pipe()`` and ``decrypt_pipe()`` methods for use in 54 | certain applications. I haven't put together an example using 55 | them yet, but it should be straightforward. 56 | 57 | Protocol Update 58 | --------------- 59 | pyaxo 0.4 was updated according to the Oct 1, 2014 version 60 | of the protocol, which changed the order of the ratcheting. For that 61 | reason, old conversations (created with pyaxo < 0.4) might not work 62 | properly after the update. We suggest that users update pyaxo and 63 | restart their conversations. 64 | 65 | Bugs, etc. should be reported to the *pyaxo* github `issues page`_. 66 | 67 | .. _`issues page`: https://github.com/rxcomm/pyaxo/issues 68 | .. _`passlib`: https://pypi.python.org/pypi/passlib 69 | .. _`pynacl`: https://pypi.python.org/pypi/PyNaCl/ 70 | .. _`pip`: https://pypi.python.org/pypi/pip 71 | .. _`setuptools`: https://pypi.python.org/pypi/setuptools 72 | .. _`Open Whisper Systems Blog`: https://whispersystems.org/blog/advanced-ratcheting/ 73 | -------------------------------------------------------------------------------- /tests/utils.py: -------------------------------------------------------------------------------- 1 | import errno 2 | import os 3 | 4 | 5 | DEFAULT_DB = './axolotl.db' 6 | 7 | PLAINTEXT = 'message {}' 8 | 9 | EXCHANGE_IDS = list() 10 | EXCHANGES = list() 11 | 12 | 13 | def remove_db(file_path=DEFAULT_DB): 14 | try: 15 | os.remove(file_path) 16 | except OSError as e: 17 | if e.errno != errno.ENOENT: 18 | raise 19 | 20 | 21 | def encrypt(axolotl, i, pt, ct): 22 | ct.append(axolotl.encrypt(pt[i])) 23 | 24 | 25 | def decrypt(axolotl, i, pt, ct): 26 | assert axolotl.decrypt(ct[i]) == pt[i] 27 | 28 | 29 | def exchange_0(a, b): 30 | pt = [PLAINTEXT.format(i) for i in range(14)] 31 | ct = list() 32 | 33 | encrypt(a, 0, pt, ct) 34 | encrypt(a, 1, pt, ct) 35 | encrypt(b, 2, pt, ct) 36 | decrypt(b, 0, pt, ct) 37 | decrypt(b, 1, pt, ct) 38 | decrypt(a, 2, pt, ct) 39 | encrypt(a, 3, pt, ct) 40 | encrypt(a, 4, pt, ct) 41 | encrypt(b, 5, pt, ct) 42 | encrypt(a, 6, pt, ct) 43 | encrypt(b, 7, pt, ct) 44 | encrypt(a, 8, pt, ct) 45 | encrypt(a, 9, pt, ct) 46 | encrypt(a, 10, pt, ct) 47 | encrypt(a, 11, pt, ct) 48 | decrypt(b, 11, pt, ct) 49 | decrypt(b, 3, pt, ct) 50 | decrypt(b, 9, pt, ct) 51 | decrypt(a, 5, pt, ct) 52 | decrypt(a, 7, pt, ct) 53 | decrypt(b, 4, pt, ct) 54 | encrypt(b, 12, pt, ct) 55 | decrypt(a, 12, pt, ct) 56 | encrypt(a, 13, pt, ct) 57 | decrypt(b, 13, pt, ct) 58 | decrypt(b, 6, pt, ct) 59 | 60 | 61 | def exchange_1(a, b): 62 | n = 3 63 | pt = list() 64 | ct = list() 65 | 66 | for i in range(n): 67 | pt.append(PLAINTEXT.format(i)) 68 | encrypt(a, i, pt, ct) 69 | 70 | for i in range(n): 71 | decrypt(b, i, pt, ct) 72 | 73 | for i in range(n, n*2): 74 | pt.append(PLAINTEXT.format(i)) 75 | encrypt(b, i, pt, ct) 76 | 77 | for i in range(n, n*2): 78 | decrypt(a, i, pt, ct) 79 | 80 | 81 | def exchange_2(a, b): 82 | n = 3 83 | pt = list() 84 | ct = list() 85 | 86 | for i in range(n): 87 | pt.append(PLAINTEXT.format(i)) 88 | encrypt(a, i, pt, ct) 89 | 90 | for i in reversed(range(n)): 91 | decrypt(b, i, pt, ct) 92 | 93 | for i in range(n, n*2): 94 | pt.append(PLAINTEXT.format(i)) 95 | encrypt(b, i, pt, ct) 96 | 97 | for i in reversed(range(n, n*2)): 98 | decrypt(a, i, pt, ct) 99 | 100 | 101 | def exchange_3(a, b): 102 | pt = [PLAINTEXT.format(i) for i in range(6)] 103 | ct = list() 104 | 105 | encrypt(a, 0, pt, ct) 106 | decrypt(b, 0, pt, ct) 107 | encrypt(b, 1, pt, ct) 108 | decrypt(a, 1, pt, ct) 109 | encrypt(a, 2, pt, ct) 110 | encrypt(a, 3, pt, ct) 111 | decrypt(b, 2, pt, ct) 112 | encrypt(b, 4, pt, ct) 113 | decrypt(a, 4, pt, ct) 114 | encrypt(a, 5, pt, ct) 115 | decrypt(b, 5, pt, ct) 116 | decrypt(b, 3, pt, ct) 117 | 118 | 119 | for i in range(4): 120 | id_ = 'exchange_{}'.format(i) 121 | EXCHANGE_IDS.append(id_) 122 | EXCHANGES.append(globals()[id_]) 123 | -------------------------------------------------------------------------------- /examples/transfer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | This file transfer example demonstrates a couple of things: 5 | 1) Transferring files using Axolotl to encrypt each block of the transfer 6 | with a different ephemeral key. 7 | 2) Using a context manager with Axolotl. 8 | 9 | The utility will prompt you for the location of the Axolotl key database 10 | and the blocksize. The blocksize must be chosen so that the maximum number 11 | of blocks is <= 255. Security is optimized by a larger number of blocks, 12 | and transfer speed is optimized by a smaller number of blocks. If you 13 | choose incorrectly, the utility will prompt you with a recommendation. 14 | 15 | Key databases can be generated using e.g the init_conversation.py utility. 16 | 17 | Syntax for receive is: ./transfer.py -r 18 | 19 | Syntax for send is: ./transfer.py -s 20 | 21 | The end of packet (EOP) and end of file (EOF) markers I use are pretty simple, 22 | but unlikely to show up in ciphertext. 23 | """ 24 | 25 | 26 | from pyaxo import Axolotl 27 | from contextlib import contextmanager 28 | import sys 29 | import socket 30 | import os 31 | 32 | try: 33 | location = raw_input('Database directory (default ~/.bin)? ').strip() 34 | if location == '': location = '~/.bin' 35 | location = os.path.expanduser(location) 36 | if sys.argv[1] == '-s': 37 | file_name = sys.argv[2] 38 | host = sys.argv[3] 39 | size = int(raw_input('File transfer block size? ')) 40 | port = 50000 41 | except IndexError: 42 | print 'Usage: ' + sys.argv[0] + ' -(s,r) [ ]' 43 | exit() 44 | 45 | backlog = 1 46 | 47 | @contextmanager 48 | def socketcontext(*args, **kwargs): 49 | s = socket.socket(*args, **kwargs) 50 | yield s 51 | s.close() 52 | 53 | @contextmanager 54 | def axo(my_name, other_name, dbname, dbpassphrase): 55 | a = Axolotl(my_name, dbname=dbname, dbpassphrase=dbpassphrase) 56 | a.loadState(my_name, other_name) 57 | yield a 58 | a.saveState() 59 | 60 | if sys.argv[1] == '-s': 61 | # open socket and send data 62 | with socketcontext(socket.AF_INET, socket.SOCK_STREAM) as s: 63 | s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 64 | s.connect((host, port)) 65 | with axo('send', 'receive', dbname=location+'/send.db', dbpassphrase='1') as a: 66 | with open(file_name, 'rb') as f: 67 | plaintext = f.read() 68 | plainlength = len(plaintext) 69 | while plainlength/size > 253: 70 | print 'File too large to transfer - increase size parameter' 71 | print 'Recommended >= ' + str(plainlength/128) + ' bytes per block' 72 | size = int(raw_input('File transfer block size? ')) 73 | plaintext = str(len(file_name)).zfill(2) + file_name + plaintext 74 | while len(plaintext) > size: 75 | msg = plaintext[:size] 76 | if msg == '': break 77 | plaintext = plaintext[size:] 78 | ciphertext = a.encrypt(msg) 79 | s.send(ciphertext + 'EOP') 80 | if len(plaintext) != 0: 81 | ciphertext = a.encrypt(plaintext) 82 | s.send(ciphertext + 'EOF') 83 | 84 | # receive confirmation 85 | confirmation = s.recv(1024) 86 | if a.decrypt(confirmation) == 'Got It!': 87 | print 'Transfer confirmed!' 88 | else: 89 | print 'Transfer not confirmed...' 90 | 91 | if sys.argv[1] == '-r': 92 | # open socket and receive data 93 | with socketcontext(socket.AF_INET, socket.SOCK_STREAM) as s: 94 | s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 95 | host = '' 96 | s.bind((host, port)) 97 | s.listen(backlog) 98 | client, address = s.accept() 99 | with axo('receive', 'send', dbname=location+'/receive.db', dbpassphrase='1') as a: 100 | plaintext = '' 101 | ciphertext = '' 102 | while True: 103 | newtext = client.recv(1024) 104 | ciphertext += newtext 105 | if ciphertext[-3:] == 'EOF': break 106 | if ciphertext == '': 107 | print 'nothing received' 108 | exit() 109 | cipherlist = ciphertext.split('EOP') 110 | for item in cipherlist: 111 | if item[-3:] == 'EOF': 112 | item = item[:-3] 113 | plaintext += a.decrypt(item) 114 | filenamelength = int(plaintext[:2]) 115 | file_name = plaintext[2:2+filenamelength] 116 | with open(file_name, 'wb') as f: 117 | f.write(plaintext[2+filenamelength:]) 118 | 119 | # send confirmation 120 | reply = a.encrypt('Got It!') 121 | client.send(reply) 122 | 123 | print file_name + ' received' 124 | -------------------------------------------------------------------------------- /examples/axochat.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import hashlib 4 | import socket 5 | import threading 6 | import sys 7 | import curses 8 | from curses.textpad import Textbox 9 | from random import randint 10 | from contextlib import contextmanager 11 | from pyaxo import Axolotl 12 | from time import sleep 13 | from getpass import getpass 14 | from binascii import a2b_base64 as a2b 15 | from binascii import b2a_base64 as b2a 16 | 17 | """ 18 | Standalone chat script using libsodium for encryption with the Axolotl 19 | ratchet for key management. 20 | 21 | Usage: 22 | 1. One side starts the server with: 23 | axochat.py -s 24 | 25 | 2. The other side connects the client to the server with: 26 | axochat.py -c 27 | 28 | 3. Both sides need to input the same master key. This can be any 29 | alphanumeric string. Also, the server will generate a handshake 30 | key that is a required input for the client. 31 | 32 | 4. .quit at the chat prompt will quit (don't forget the "dot") 33 | 34 | Port 50000 is the default port, but you can choose your own port as well. 35 | 36 | Axochat requires the Axolotl module at https://github.com/rxcomm/pyaxo 37 | 38 | Copyright (C) 2014-2016 by David R. Andersen 39 | 40 | This program is free software: you can redistribute it and/or modify 41 | it under the terms of the GNU General Public License as published by 42 | the Free Software Foundation, either version 3 of the License, or 43 | (at your option) any later version. 44 | 45 | This program is distributed in the hope that it will be useful, 46 | but WITHOUT ANY WARRANTY; without even the implied warranty of 47 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 48 | GNU General Public License for more details. 49 | 50 | You should have received a copy of the GNU General Public License 51 | along with this program. If not, see . 52 | """ 53 | 54 | @contextmanager 55 | def socketcontext(*args, **kwargs): 56 | s = socket.socket(*args, **kwargs) 57 | s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 58 | s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) 59 | yield s 60 | s.close() 61 | 62 | class _Textbox(Textbox): 63 | """ 64 | curses.textpad.Textbox requires users to ^g on completion, which is sort 65 | of annoying for an interactive chat client such as this, which typically only 66 | reuquires an enter. This subclass fixes this problem by signalling completion 67 | on Enter as well as ^g. Also, map key to ^h. 68 | """ 69 | def __init__(*args, **kwargs): 70 | Textbox.__init__(*args, **kwargs) 71 | 72 | def do_command(self, ch): 73 | if ch == 10: # Enter 74 | return 0 75 | if ch == 127: # Enter 76 | return 8 77 | return Textbox.do_command(self, ch) 78 | 79 | def validator(ch): 80 | """ 81 | Update screen if necessary and release the lock so receiveThread can run 82 | """ 83 | global screen_needs_update 84 | try: 85 | if screen_needs_update: 86 | curses.doupdate() 87 | screen_needs_update = False 88 | return ch 89 | finally: 90 | lock.release() 91 | sleep(0.01) # let receiveThread in if necessary 92 | lock.acquire() 93 | 94 | def windows(): 95 | stdscr = curses.initscr() 96 | curses.noecho() 97 | curses.start_color() 98 | curses.use_default_colors() 99 | curses.init_pair(3, 2, -1) 100 | curses.cbreak() 101 | curses.curs_set(1) 102 | (sizey, sizex) = stdscr.getmaxyx() 103 | input_win = curses.newwin(8, sizex, sizey-8, 0) 104 | output_win = curses.newwin(sizey-8, sizex, 0, 0) 105 | input_win.idlok(1) 106 | input_win.scrollok(1) 107 | input_win.nodelay(1) 108 | input_win.leaveok(0) 109 | input_win.timeout(100) 110 | input_win.attron(curses.color_pair(3)) 111 | output_win.idlok(1) 112 | output_win.scrollok(1) 113 | output_win.leaveok(0) 114 | return stdscr, input_win, output_win 115 | 116 | def closeWindows(stdscr): 117 | curses.nocbreak() 118 | stdscr.keypad(0) 119 | curses.echo() 120 | curses.endwin() 121 | 122 | def usage(): 123 | print 'Usage: ' + sys.argv[0] + ' -(s,c)' 124 | print ' -s: start a chat in server mode' 125 | print ' -c: start a chat in client mode' 126 | exit() 127 | 128 | def receiveThread(sock, stdscr, input_win, output_win): 129 | global screen_needs_update, a 130 | while True: 131 | data = '' 132 | while data[-3:] != 'EOP': 133 | rcv = sock.recv(1024) 134 | if not rcv: 135 | input_win.move(0, 0) 136 | input_win.addstr('Disconnected - Ctrl-C to exit!') 137 | input_win.refresh() 138 | sys.exit() 139 | data = data + rcv 140 | data_list = data.split('EOP') 141 | lock.acquire() 142 | (cursory, cursorx) = input_win.getyx() 143 | for data in data_list: 144 | if data != '': 145 | output_win.addstr(a.decrypt(data)) 146 | input_win.move(cursory, cursorx) 147 | input_win.cursyncup() 148 | input_win.noutrefresh() 149 | output_win.noutrefresh() 150 | sleep(0.01) # write time for axo db 151 | screen_needs_update = True 152 | lock.release() 153 | 154 | def chatThread(sock): 155 | global screen_needs_update, a 156 | stdscr, input_win, output_win = windows() 157 | input_win.addstr(0, 0, NICK + ':> ') 158 | textpad = _Textbox(input_win, insert_mode=True) 159 | textpad.stripspaces = True 160 | t = threading.Thread(target=receiveThread, args=(sock, stdscr, input_win,output_win)) 161 | t.daemon = True 162 | t.start() 163 | try: 164 | while True: 165 | lock.acquire() 166 | data = textpad.edit(validator) 167 | if NICK+':> .quit' in data: 168 | closeWindows(stdscr) 169 | sys.exit() 170 | input_win.clear() 171 | input_win.addstr(NICK+':> ') 172 | output_win.addstr(data.replace('\n', '') + '\n', curses.color_pair(3)) 173 | output_win.noutrefresh() 174 | input_win.move(0, len(NICK)+3) 175 | input_win.cursyncup() 176 | input_win.noutrefresh() 177 | screen_needs_update = True 178 | data = data.replace('\n', '') + '\n' 179 | try: 180 | sock.send(a.encrypt(data) + 'EOP') 181 | except socket.error: 182 | input_win.addstr('Disconnected') 183 | input_win.refresh() 184 | closeWindows(stdscr) 185 | sys.exit() 186 | sleep(0.01) # write time for axo db 187 | lock.release() 188 | except KeyboardInterrupt: 189 | closeWindows(stdscr) 190 | 191 | def getPasswd(nick): 192 | return '1' 193 | 194 | if __name__ == '__main__': 195 | global a 196 | try: 197 | mode = sys.argv[1] 198 | except: 199 | usage() 200 | 201 | NICK = raw_input('Enter your nick: ') 202 | OTHER_NICK = raw_input('Enter the nick of the other party: ') 203 | mkey = getpass('Enter the master key: ') 204 | lock = threading.Lock() 205 | screen_needs_update = False 206 | HOST = '' 207 | while True: 208 | try: 209 | PORT = raw_input('TCP port (1 for random choice, 50000 is default): ') 210 | PORT = int(PORT) 211 | break 212 | except ValueError: 213 | PORT = 50000 214 | break 215 | if PORT >= 1025 and PORT <= 65535: 216 | pass 217 | elif PORT == 1: 218 | PORT = 1025 + randint(0, 64510) 219 | print 'PORT is ' + str(PORT) 220 | 221 | if mode == '-s': 222 | a = Axolotl(NICK, 223 | dbname=OTHER_NICK+'.db', 224 | dbpassphrase=None, 225 | nonthreaded_sql=False) 226 | a.createState(other_name=OTHER_NICK, 227 | mkey=hashlib.sha256(mkey).digest(), 228 | mode=False) 229 | print 'Your ratchet key is: %s' % b2a(a.state['DHRs']).strip() 230 | print 'Send this to %s...' % OTHER_NICK 231 | 232 | print 'Waiting for ' + OTHER_NICK + ' to connect...' 233 | with socketcontext(socket.AF_INET, socket.SOCK_STREAM) as s: 234 | s.bind((HOST, PORT)) 235 | s.listen(1) 236 | conn, addr = s.accept() 237 | chatThread(conn) 238 | 239 | elif mode == '-c': 240 | rkey = raw_input('Enter %s\'s ratchet key: ' % OTHER_NICK) 241 | a = Axolotl(NICK, 242 | dbname=OTHER_NICK+'.db', 243 | dbpassphrase=None, 244 | nonthreaded_sql=False) 245 | a.createState(other_name=OTHER_NICK, 246 | mkey=hashlib.sha256(mkey).digest(), 247 | mode=True, 248 | other_ratchetKey=a2b(rkey)) 249 | 250 | HOST = raw_input('Enter the server: ') 251 | print 'Connecting to ' + HOST + '...' 252 | with socketcontext(socket.AF_INET, socket.SOCK_STREAM) as s: 253 | s.connect((HOST, PORT)) 254 | chatThread(s) 255 | 256 | else: 257 | usage() 258 | -------------------------------------------------------------------------------- /tests/test_db.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | from copy import deepcopy 3 | 4 | import pytest 5 | 6 | from pyaxo import Axolotl 7 | 8 | from . import utils 9 | 10 | 11 | PASSPHRASES = [None, '123', '321'] 12 | 13 | 14 | class TestDefaultDatabase: 15 | dbs = [utils.DEFAULT_DB] 16 | 17 | def test_shared_db(self): 18 | # create two instance classes - one which will share its database 19 | # (note that Dick and Harry's passphrases must match or Harry won't 20 | # be able to load Dick's saved database) 21 | shared_pass = 'shared passphrase' 22 | tom = Axolotl('Tom', dbpassphrase="tom's passphrase") 23 | dick = Axolotl('Dick', dbpassphrase=shared_pass) 24 | 25 | # initialize Tom and Dick's states 26 | tom.initState(other_name=dick.name, 27 | other_identityKey=dick.state['DHIs'], 28 | other_handshakeKey=dick.handshakePKey, 29 | other_ratchetKey=dick.state['DHRs'], 30 | verify=False) 31 | dick.initState(other_name=tom.name, 32 | other_identityKey=tom.state['DHIs'], 33 | other_handshakeKey=tom.handshakePKey, 34 | other_ratchetKey=tom.state['DHRs'], 35 | verify=False) 36 | 37 | # get the plaintext 38 | msg = 'plaintext' 39 | 40 | # Tom encrypts it to Dick 41 | ciphertext = tom.encrypt(msg) 42 | 43 | # save Dick's state prior to decrypting the message 44 | dick.saveState() 45 | 46 | # Dick decrypts the ciphertext 47 | assert dick.decrypt(ciphertext) == msg 48 | 49 | # now load Dick's state to Harry 50 | harry = Axolotl('Harry', dbpassphrase=shared_pass) 51 | harry.loadState(dick.name, tom.name) 52 | 53 | # Harry decrypts the ciphertext 54 | assert harry.decrypt(ciphertext) == msg 55 | 56 | @pytest.mark.parametrize('passphrase_1', PASSPHRASES) 57 | @pytest.mark.parametrize('passphrase_0', PASSPHRASES) 58 | def test_passphrase(self, passphrase_0, passphrase_1): 59 | a = Axolotl('Angie', dbpassphrase=passphrase_0) 60 | b = Axolotl('Barb', dbpassphrase=None) 61 | 62 | a.initState(other_name=b.name, 63 | other_identityKey=b.state['DHIs'], 64 | other_handshakeKey=b.handshakePKey, 65 | other_ratchetKey=b.state['DHRs'], 66 | verify=False) 67 | a.saveState() 68 | 69 | if passphrase_0 == passphrase_1: 70 | a = Axolotl('Angie', dbpassphrase=passphrase_1) 71 | assert isinstance(a.db, sqlite3.Connection) 72 | else: 73 | with pytest.raises(SystemExit): 74 | a = Axolotl('Angie', dbpassphrase=passphrase_1) 75 | 76 | def test_delete_conversation( 77 | self, axolotl_a, axolotl_b, axolotl_c, 78 | a_identity_keys, b_identity_keys, c_identity_keys, 79 | a_handshake_keys, b_handshake_keys, c_handshake_keys, 80 | a_ratchet_keys, b_ratchet_keys, c_ratchet_keys): 81 | conv_b = axolotl_a.init_conversation( 82 | axolotl_b.name, 83 | priv_identity_key=a_identity_keys.priv, 84 | identity_key=a_identity_keys.pub, 85 | priv_handshake_key=a_handshake_keys.priv, 86 | other_identity_key=b_identity_keys.pub, 87 | other_handshake_key=b_handshake_keys.pub, 88 | priv_ratchet_key=a_ratchet_keys.priv, 89 | ratchet_key=a_ratchet_keys.pub, 90 | other_ratchet_key=b_ratchet_keys.pub) 91 | 92 | conv_b.save() 93 | conv_b.delete() 94 | 95 | assert not axolotl_a.load_conversation(axolotl_b.name) 96 | 97 | def test_get_other_names( 98 | self, axolotl_a, axolotl_b, axolotl_c, 99 | a_identity_keys, b_identity_keys, c_identity_keys, 100 | a_handshake_keys, b_handshake_keys, c_handshake_keys, 101 | a_ratchet_keys, b_ratchet_keys, c_ratchet_keys): 102 | conv_b = axolotl_a.init_conversation( 103 | axolotl_b.name, 104 | priv_identity_key=a_identity_keys.priv, 105 | identity_key=a_identity_keys.pub, 106 | priv_handshake_key=a_handshake_keys.priv, 107 | other_identity_key=b_identity_keys.pub, 108 | other_handshake_key=b_handshake_keys.pub, 109 | priv_ratchet_key=a_ratchet_keys.priv, 110 | ratchet_key=a_ratchet_keys.pub, 111 | other_ratchet_key=b_ratchet_keys.pub) 112 | 113 | conv_c = axolotl_a.init_conversation( 114 | axolotl_c.name, 115 | priv_identity_key=a_identity_keys.priv, 116 | identity_key=a_identity_keys.pub, 117 | priv_handshake_key=a_handshake_keys.priv, 118 | other_identity_key=c_identity_keys.pub, 119 | other_handshake_key=c_handshake_keys.pub, 120 | priv_ratchet_key=a_ratchet_keys.priv, 121 | ratchet_key=a_ratchet_keys.pub, 122 | other_ratchet_key=c_ratchet_keys.pub) 123 | 124 | conv_b.save() 125 | conv_c.save() 126 | 127 | assert (sorted(axolotl_a.get_other_names()) == 128 | sorted([axolotl_b.name, axolotl_c.name])) 129 | 130 | 131 | class TestIndividualDatabases: 132 | dbs = ['angie.db', 'barb.db'] 133 | 134 | def test_individual_dbs(self, exchange): 135 | # create two instance classes with encrypted databases 136 | a = Axolotl('angie', dbname=self.dbs[0], dbpassphrase=self.dbs[0]) 137 | b = Axolotl('barb', dbname=self.dbs[1], dbpassphrase=self.dbs[1]) 138 | 139 | # initialize the states 140 | a.initState(other_name=b.name, 141 | other_identityKey=b.state['DHIs'], 142 | other_handshakeKey=b.handshakePKey, 143 | other_ratchetKey=b.state['DHRs'], 144 | verify=False) 145 | b.initState(other_name=a.name, 146 | other_identityKey=a.state['DHIs'], 147 | other_handshakeKey=a.handshakePKey, 148 | other_ratchetKey=a.state['DHRs'], 149 | verify=False) 150 | 151 | # save the states 152 | a.saveState() 153 | b.saveState() 154 | 155 | # reload the databases 156 | a = Axolotl('angie', dbname=self.dbs[0], dbpassphrase=self.dbs[0]) 157 | b = Axolotl('barb', dbname=self.dbs[1], dbpassphrase=self.dbs[1]) 158 | 159 | # load their states 160 | a.loadState(a.name, b.name) 161 | b.loadState(b.name, a.name) 162 | 163 | # send some messages back and forth 164 | exchange(a, b) 165 | 166 | def test_persist_skipped_mk( 167 | self, a_identity_keys, a_handshake_keys, a_ratchet_keys, 168 | b_identity_keys, b_handshake_keys, b_ratchet_keys): 169 | a = Axolotl('angie', dbname=self.dbs[0], dbpassphrase=self.dbs[0]) 170 | b = Axolotl('barb', dbname=self.dbs[1], dbpassphrase=self.dbs[1]) 171 | 172 | conv_a = a.init_conversation( 173 | b.name, 174 | priv_identity_key=a_identity_keys.priv, 175 | identity_key=a_identity_keys.pub, 176 | priv_handshake_key=a_handshake_keys.priv, 177 | other_identity_key=b_identity_keys.pub, 178 | other_handshake_key=b_handshake_keys.pub, 179 | priv_ratchet_key=a_ratchet_keys.priv, 180 | ratchet_key=a_ratchet_keys.pub, 181 | other_ratchet_key=b_ratchet_keys.pub) 182 | 183 | conv_b = b.init_conversation( 184 | a.name, 185 | priv_identity_key=b_identity_keys.priv, 186 | identity_key=b_identity_keys.pub, 187 | priv_handshake_key=b_handshake_keys.priv, 188 | other_identity_key=a_identity_keys.pub, 189 | other_handshake_key=a_handshake_keys.pub, 190 | priv_ratchet_key=b_ratchet_keys.priv, 191 | ratchet_key=b_ratchet_keys.pub, 192 | other_ratchet_key=a_ratchet_keys.pub) 193 | 194 | pt = [utils.PLAINTEXT.format(i) for i in range(5)] 195 | ct = list() 196 | 197 | utils.encrypt(conv_a, 0, pt, ct) 198 | utils.decrypt(conv_b, 0, pt, ct) 199 | utils.encrypt(conv_a, 1, pt, ct) 200 | utils.encrypt(conv_a, 2, pt, ct) 201 | utils.decrypt(conv_b, 2, pt, ct) 202 | utils.encrypt(conv_a, 3, pt, ct) 203 | utils.encrypt(conv_a, 4, pt, ct) 204 | utils.decrypt(conv_b, 4, pt, ct) 205 | 206 | # make sure there are staged skipped keys 207 | assert conv_b.staged_hk_mk 208 | 209 | # save the database, copy the staged keys dict and delete the objects 210 | conv_b.save() 211 | persisted_hk_mk = deepcopy(conv_b.staged_hk_mk) 212 | del b, conv_b 213 | 214 | # load the conversation from disk 215 | B = Axolotl('barb', dbname=self.dbs[1], dbpassphrase=self.dbs[1]) 216 | conv_B = B.load_conversation(a.name) 217 | 218 | # assert both dicts have the same content 219 | assert conv_B.staged_hk_mk.keys() == persisted_hk_mk.keys() 220 | for mk in conv_B.staged_hk_mk: 221 | assert conv_B.staged_hk_mk[mk].mk == persisted_hk_mk[mk].mk 222 | assert conv_B.staged_hk_mk[mk].hk == persisted_hk_mk[mk].hk 223 | assert (conv_B.staged_hk_mk[mk].timestamp == 224 | persisted_hk_mk[mk].timestamp) 225 | 226 | # decrypt the skipped messages 227 | utils.decrypt(conv_B, 1, pt, ct) 228 | utils.decrypt(conv_B, 3, pt, ct) 229 | 230 | 231 | @pytest.fixture(autouse=True) 232 | def setup_teardown_dbs(request): 233 | remove_dbs(request.cls.dbs) 234 | yield 235 | remove_dbs(request.cls.dbs) 236 | 237 | 238 | def remove_dbs(dbs): 239 | for db in dbs: 240 | utils.remove_db(db) 241 | -------------------------------------------------------------------------------- /examples/smp.py: -------------------------------------------------------------------------------- 1 | """ 2 | Code is based on: 3 | https://github.com/shanet/Cryptully/blob/master/src/crypto/smp.py 4 | originally written by Shane Tully and released under the LGPL. 5 | """ 6 | import hashlib 7 | import os 8 | import random 9 | import struct 10 | 11 | class SMP(object): 12 | def __init__(self, secret=None): 13 | # 4096-bit safe prime (RFC 3526) 14 | self.mod = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199FFFFFFFFFFFFFFFF 15 | self.modOrder = (self.mod-1) / 2 16 | self.gen = 2 17 | self.match = False 18 | 19 | self.secret = sha256(secret) 20 | 21 | def step1(self): 22 | self.x2 = createRandomExponent() 23 | self.x3 = createRandomExponent() 24 | 25 | self.g2 = pow(self.gen, self.x2, self.mod) 26 | self.g3 = pow(self.gen, self.x3, self.mod) 27 | 28 | (c1, d1) = self.createLogProof('1', self.x2) 29 | (c2, d2) = self.createLogProof('2', self.x3) 30 | 31 | # Send g2a, g3a, c1, d1, c2, d2 32 | return packList(self.g2, self.g3, c1, d1, c2, d2) 33 | 34 | def step2(self, buff): 35 | (g2a, g3a, c1, d1, c2, d2) = unpackList(buff) 36 | 37 | if not self.isValidArgument(g2a) or not self.isValidArgument(g3a): 38 | raise ValueError("Invalid g2a/g3a values") 39 | 40 | if not self.checkLogProof('1', g2a, c1, d1): 41 | raise ValueError("Proof 1 check failed") 42 | 43 | if not self.checkLogProof('2', g3a, c2, d2): 44 | raise ValueError("Proof 2 check failed") 45 | 46 | self.g2a = g2a 47 | self.g3a = g3a 48 | 49 | self.x2 = createRandomExponent() 50 | self.x3 = createRandomExponent() 51 | 52 | r = createRandomExponent() 53 | 54 | self.g2 = pow(self.gen, self.x2, self.mod) 55 | self.g3 = pow(self.gen, self.x3, self.mod) 56 | 57 | (c3, d3) = self.createLogProof('3', self.x2) 58 | (c4, d4) = self.createLogProof('4', self.x3) 59 | 60 | self.gb2 = pow(self.g2a, self.x2, self.mod) 61 | self.gb3 = pow(self.g3a, self.x3, self.mod) 62 | 63 | self.pb = pow(self.gb3, r, self.mod) 64 | self.qb = mulm(pow(self.gen, r, self.mod), pow(self.gb2, self.secret, self.mod), self.mod) 65 | 66 | (c5, d5, d6) = self.createCoordsProof('5', self.gb2, self.gb3, r) 67 | 68 | # Sends g2b, g3b, pb, qb, all the c's and d's 69 | return packList(self.g2, self.g3, self.pb, self.qb, c3, d3, c4, d4, c5, d5, d6) 70 | 71 | def step3(self, buff): 72 | (g2b, g3b, pb, qb, c3, d3, c4, d4, c5, d5, d6) = unpackList(buff) 73 | 74 | if not self.isValidArgument(g2b) or not self.isValidArgument(g3b) or \ 75 | not self.isValidArgument(pb) or not self.isValidArgument(qb): 76 | raise ValueError("Invalid g2b/g3b/pb/qb values") 77 | 78 | if not self.checkLogProof('3', g2b, c3, d3): 79 | raise ValueError("Proof 3 check failed") 80 | 81 | if not self.checkLogProof('4', g3b, c4, d4): 82 | raise ValueError("Proof 4 check failed") 83 | 84 | self.g2b = g2b 85 | self.g3b = g3b 86 | 87 | self.ga2 = pow(self.g2b, self.x2, self.mod) 88 | self.ga3 = pow(self.g3b, self.x3, self.mod) 89 | 90 | if not self.checkCoordsProof('5', c5, d5, d6, self.ga2, self.ga3, pb, qb): 91 | raise ValueError("Proof 5 check failed") 92 | 93 | s = createRandomExponent() 94 | 95 | self.qb = qb 96 | self.pb = pb 97 | self.pa = pow(self.ga3, s, self.mod) 98 | self.qa = mulm(pow(self.gen, s, self.mod), pow(self.ga2, self.secret, self.mod), self.mod) 99 | 100 | (c6, d7, d8) = self.createCoordsProof('6', self.ga2, self.ga3, s) 101 | 102 | inv = self.invm(qb) 103 | self.ra = pow(mulm(self.qa, inv, self.mod), self.x3, self.mod) 104 | 105 | (c7, d9) = self.createEqualLogsProof('7', self.qa, inv, self.x3) 106 | 107 | # Sends pa, qa, ra, c6, d7, d8, c7, d9 108 | return packList(self.pa, self.qa, self.ra, c6, d7, d8, c7, d9) 109 | 110 | def step4(self, buff): 111 | (pa, qa, ra, c6, d7, d8, c7, d9) = unpackList(buff) 112 | 113 | if not self.isValidArgument(pa) or not self.isValidArgument(qa) or not self.isValidArgument(ra): 114 | raise ValueError("Invalid pa/qa/ra values") 115 | 116 | if not self.checkCoordsProof('6', c6, d7, d8, self.gb2, self.gb3, pa, qa): 117 | raise ValueError("Proof 6 check failed") 118 | 119 | if not self.checkEqualLogs('7', c7, d9, self.g3a, mulm(qa, self.invm(self.qb), self.mod), ra): 120 | raise ValueError("Proof 7 check failed") 121 | 122 | inv = self.invm(self.qb) 123 | rb = pow(mulm(qa, inv, self.mod), self.x3, self.mod) 124 | 125 | (c8, d10) = self.createEqualLogsProof('8', qa, inv, self.x3) 126 | 127 | rab = pow(ra, self.x3, self.mod) 128 | 129 | inv = self.invm(self.pb) 130 | if rab == mulm(pa, inv, self.mod): 131 | self.match = True 132 | 133 | # Send rb, c8, d10 134 | return packList(rb, c8, d10) 135 | 136 | def step5(self, buff): 137 | (rb, c8, d10) = unpackList(buff) 138 | 139 | if not self.isValidArgument(rb): 140 | raise ValueError("Invalid rb values") 141 | 142 | if not self.checkEqualLogs('8', c8, d10, self.g3b, mulm(self.qa, self.invm(self.qb), self.mod), rb): 143 | raise ValueError("Proof 8 check failed") 144 | 145 | rab = pow(rb, self.x3, self.mod) 146 | 147 | inv = self.invm(self.pb) 148 | if rab == mulm(self.pa, inv, self.mod): 149 | self.match = True 150 | 151 | def createLogProof(self, version, x): 152 | randExponent = createRandomExponent() 153 | c = sha256(version + str(pow(self.gen, randExponent, self.mod))) 154 | d = (randExponent - mulm(x, c, self.modOrder)) % self.modOrder 155 | return (c, d) 156 | 157 | def checkLogProof(self, version, g, c, d): 158 | gd = pow(self.gen, d, self.mod) 159 | gc = pow(g, c, self.mod) 160 | gdgc = gd * gc % self.mod 161 | return (sha256(version + str(gdgc)) == c) 162 | 163 | def createCoordsProof(self, version, g2, g3, r): 164 | r1 = createRandomExponent() 165 | r2 = createRandomExponent() 166 | 167 | tmp1 = pow(g3, r1, self.mod) 168 | tmp2 = mulm(pow(self.gen, r1, self.mod), pow(g2, r2, self.mod), self.mod) 169 | 170 | c = sha256(version + str(tmp1) + str(tmp2)) 171 | 172 | # TODO: make a subm function 173 | d1 = (r1 - mulm(r, c, self.modOrder)) % self.modOrder 174 | d2 = (r2 - mulm(self.secret, c, self.modOrder)) % self.modOrder 175 | 176 | return (c, d1, d2) 177 | 178 | def checkCoordsProof(self, version, c, d1, d2, g2, g3, p, q): 179 | tmp1 = mulm(pow(g3, d1, self.mod), pow(p, c, self.mod), self.mod) 180 | 181 | tmp2 = mulm(mulm(pow(self.gen, d1, self.mod), pow(g2, d2, self.mod), self.mod), pow(q, c, self.mod), self.mod) 182 | 183 | cprime = sha256(version + str(tmp1) + str(tmp2)) 184 | 185 | return (c == cprime) 186 | 187 | def createEqualLogsProof(self, version, qa, qb, x): 188 | r = createRandomExponent() 189 | tmp1 = pow(self.gen, r, self.mod) 190 | qab = mulm(qa, qb, self.mod) 191 | tmp2 = pow(qab, r, self.mod) 192 | 193 | c = sha256(version + str(tmp1) + str(tmp2)) 194 | tmp1 = mulm(x, c, self.modOrder) 195 | d = (r - tmp1) % self.modOrder 196 | 197 | return (c, d) 198 | 199 | def checkEqualLogs(self, version, c, d, g3, qab, r): 200 | tmp1 = mulm(pow(self.gen, d, self.mod), pow(g3, c, self.mod), self.mod) 201 | 202 | tmp2 = mulm(pow(qab, d, self.mod), pow(r, c, self.mod), self.mod) 203 | 204 | cprime = sha256(version + str(tmp1) + str(tmp2)) 205 | return (c == cprime) 206 | 207 | def invm(self, x): 208 | return pow(x, self.mod-2, self.mod) 209 | 210 | def isValidArgument(self, val): 211 | return (val >= 2 and val <= self.mod-2) 212 | 213 | def packList(*items): 214 | buff = '' 215 | 216 | # For each item in the list, convert it to a byte string and add its length as a prefix 217 | for item in items: 218 | bytes = longToBytes(item) 219 | buff += struct.pack('!I', len(bytes)) + bytes 220 | 221 | return buff 222 | 223 | def unpackList(buff): 224 | items = [] 225 | 226 | index = 0 227 | while index < len(buff): 228 | # Get the length of the long (4 byte int before the actual long) 229 | length = struct.unpack('!I', buff[index:index+4])[0] 230 | index += 4 231 | 232 | # Convert the data back to a long and add it to the list 233 | item = bytesToLong(buff[index:index+length]) 234 | items.append(item) 235 | index += length 236 | 237 | return items 238 | 239 | def bytesToLong(bytes): 240 | length = len(bytes) 241 | string = 0 242 | for i in range(length): 243 | string += byteToLong(bytes[i:i+1]) << 8*(length-i-1) 244 | return string 245 | 246 | def longToBytes(long): 247 | bytes = '' 248 | while long != 0: 249 | bytes = longToByte(long & 0xff) + bytes 250 | long >>= 8 251 | return bytes 252 | 253 | def byteToLong(byte): 254 | return struct.unpack('B', byte)[0] 255 | 256 | def longToByte(long): 257 | return struct.pack('B', long) 258 | 259 | def mulm(x, y, mod): 260 | return x * y % mod 261 | 262 | def createRandomExponent(): 263 | return random.getrandbits(512*8) 264 | 265 | def sha256(message): 266 | return long(hashlib.sha256(str(message)).hexdigest(), 16) 267 | -------------------------------------------------------------------------------- /tests/test_conversations.py: -------------------------------------------------------------------------------- 1 | from collections import namedtuple 2 | from Queue import Queue 3 | from threading import Event, Thread 4 | 5 | import pytest 6 | 7 | from pyaxo import Axolotl 8 | 9 | 10 | def test_init_conversation(axolotl_a, axolotl_b, 11 | a_identity_keys, b_identity_keys, 12 | a_handshake_keys, b_handshake_keys, 13 | a_ratchet_keys, b_ratchet_keys, 14 | exchange): 15 | conv_a = axolotl_a.init_conversation( 16 | axolotl_b.name, 17 | priv_identity_key=a_identity_keys.priv, 18 | identity_key=a_identity_keys.pub, 19 | priv_handshake_key=a_handshake_keys.priv, 20 | other_identity_key=b_identity_keys.pub, 21 | other_handshake_key=b_handshake_keys.pub, 22 | priv_ratchet_key=a_ratchet_keys.priv, 23 | ratchet_key=a_ratchet_keys.pub, 24 | other_ratchet_key=b_ratchet_keys.pub) 25 | 26 | conv_b = axolotl_b.init_conversation( 27 | axolotl_a.name, 28 | priv_identity_key=b_identity_keys.priv, 29 | identity_key=b_identity_keys.pub, 30 | priv_handshake_key=b_handshake_keys.priv, 31 | other_identity_key=a_identity_keys.pub, 32 | other_handshake_key=a_handshake_keys.pub, 33 | priv_ratchet_key=b_ratchet_keys.priv, 34 | ratchet_key=b_ratchet_keys.pub, 35 | other_ratchet_key=a_ratchet_keys.pub) 36 | 37 | exchange(conv_a, conv_b) 38 | 39 | 40 | def test_init_nonthreaded_conversations( 41 | axolotl_a, axolotl_b, axolotl_c, 42 | a_identity_keys, b_identity_keys, c_identity_keys, 43 | a_handshake_keys, b_handshake_keys, c_handshake_keys, 44 | a_ratchet_keys, b_ratchet_keys, c_ratchet_keys, 45 | exchange): 46 | conversations = initialize_conversations( 47 | axolotl_a, a_identity_keys, a_handshake_keys, a_ratchet_keys, 48 | axolotl_b, b_identity_keys, b_handshake_keys, b_ratchet_keys, 49 | axolotl_c, c_identity_keys, c_handshake_keys, c_ratchet_keys) 50 | 51 | exchange(conversations.ab, conversations.ba) 52 | exchange(conversations.ac, conversations.ca) 53 | exchange(conversations.bc, conversations.cb) 54 | 55 | 56 | def test_init_threaded_conversations( 57 | threaded_axolotl_a, threaded_axolotl_b, threaded_axolotl_c, 58 | a_identity_keys, b_identity_keys, c_identity_keys, 59 | a_handshake_keys, b_handshake_keys, c_handshake_keys, 60 | a_ratchet_keys, b_ratchet_keys, c_ratchet_keys, 61 | exchange): 62 | conversations = initialize_conversations( 63 | threaded_axolotl_a, a_identity_keys, a_handshake_keys, a_ratchet_keys, 64 | threaded_axolotl_b, b_identity_keys, b_handshake_keys, b_ratchet_keys, 65 | threaded_axolotl_c, c_identity_keys, c_handshake_keys, c_ratchet_keys) 66 | 67 | run_threaded_exchanges(exchange, conversations) 68 | 69 | 70 | def test_create_conversation(axolotl_a, axolotl_b, 71 | a_identity_keys, b_identity_keys, 72 | a_handshake_keys, b_handshake_keys, 73 | a_ratchet_keys, b_ratchet_keys, 74 | exchange): 75 | mkey = 'masterkey' 76 | 77 | conv_a = axolotl_a.create_conversation( 78 | other_name=axolotl_b.name, 79 | mkey=mkey, 80 | mode=True, 81 | priv_identity_key=a_identity_keys.priv, 82 | identity_key=a_identity_keys.pub, 83 | other_identity_key=b_identity_keys.pub, 84 | other_ratchet_key=b_ratchet_keys.pub) 85 | 86 | conv_b = axolotl_b.create_conversation( 87 | other_name=axolotl_a.name, 88 | mkey=mkey, 89 | mode=False, 90 | priv_identity_key=b_identity_keys.priv, 91 | identity_key=b_identity_keys.pub, 92 | other_identity_key=a_identity_keys.pub, 93 | priv_ratchet_key=b_ratchet_keys.priv, 94 | ratchet_key=b_ratchet_keys.pub) 95 | 96 | exchange(conv_a, conv_b) 97 | 98 | 99 | def test_create_nonthreaded_conversations( 100 | axolotl_a, axolotl_b, axolotl_c, 101 | a_identity_keys, b_identity_keys, c_identity_keys, 102 | a_handshake_keys, b_handshake_keys, c_handshake_keys, 103 | a_ratchet_keys, b_ratchet_keys, c_ratchet_keys, 104 | exchange): 105 | mkey_ab = 'masterkey_ab' 106 | mkey_ac = 'masterkey_ac' 107 | mkey_bc = 'masterkey_bc' 108 | 109 | conversations = create_conversations( 110 | axolotl_a, a_identity_keys, a_handshake_keys, a_ratchet_keys, 111 | axolotl_b, b_identity_keys, b_handshake_keys, b_ratchet_keys, 112 | axolotl_c, c_identity_keys, c_handshake_keys, c_ratchet_keys, 113 | mkey_ab, mkey_ac, mkey_bc) 114 | 115 | exchange(conversations.ab, conversations.ba) 116 | exchange(conversations.ac, conversations.ca) 117 | exchange(conversations.bc, conversations.cb) 118 | 119 | 120 | def test_create_threaded_conversations( 121 | threaded_axolotl_a, threaded_axolotl_b, threaded_axolotl_c, 122 | a_identity_keys, b_identity_keys, c_identity_keys, 123 | a_handshake_keys, b_handshake_keys, c_handshake_keys, 124 | a_ratchet_keys, b_ratchet_keys, c_ratchet_keys, 125 | exchange): 126 | mkey_ab = 'masterkey_ab' 127 | mkey_ac = 'masterkey_ac' 128 | mkey_bc = 'masterkey_bc' 129 | 130 | conversations = create_conversations( 131 | threaded_axolotl_a, a_identity_keys, a_handshake_keys, a_ratchet_keys, 132 | threaded_axolotl_b, b_identity_keys, b_handshake_keys, b_ratchet_keys, 133 | threaded_axolotl_c, c_identity_keys, c_handshake_keys, c_ratchet_keys, 134 | mkey_ab, mkey_ac, mkey_bc) 135 | 136 | run_threaded_exchanges(exchange, conversations) 137 | 138 | 139 | @pytest.fixture() 140 | def threaded_axolotl_a(): 141 | return Axolotl('Angie', dbpassphrase=None, nonthreaded_sql=False) 142 | 143 | 144 | @pytest.fixture() 145 | def threaded_axolotl_b(): 146 | return Axolotl('Barb', dbpassphrase=None, nonthreaded_sql=False) 147 | 148 | 149 | @pytest.fixture() 150 | def threaded_axolotl_c(): 151 | return Axolotl('Charlie', dbpassphrase=None, nonthreaded_sql=False) 152 | 153 | 154 | class ThreadedExchange(Thread): 155 | def __init__(self, exchange, axolotl_x, axolotl_y, event, queue): 156 | super(ThreadedExchange, self).__init__() 157 | self.daemon = True 158 | self.exchange = exchange 159 | self.axolotl_x = axolotl_x 160 | self.axolotl_y = axolotl_y 161 | self.event = event 162 | self.queue = queue 163 | 164 | def run(self): 165 | self.event.wait() 166 | try: 167 | self.exchange(self.axolotl_x, self.axolotl_y) 168 | except AssertionError: 169 | self.queue.put(False) 170 | else: 171 | self.queue.put(True) 172 | 173 | 174 | Conversations = namedtuple('Conversations', 'ab ac ba bc ca cb') 175 | 176 | 177 | def initialize_conversations( 178 | axolotl_a, a_identity_keys, a_handshake_keys, a_ratchet_keys, 179 | axolotl_b, b_identity_keys, b_handshake_keys, b_ratchet_keys, 180 | axolotl_c, c_identity_keys, c_handshake_keys, c_ratchet_keys): 181 | ab = axolotl_a.init_conversation( 182 | other_name=axolotl_b.name, 183 | priv_identity_key=a_identity_keys.priv, 184 | identity_key=a_identity_keys.pub, 185 | priv_handshake_key=a_handshake_keys.priv, 186 | other_identity_key=b_identity_keys.pub, 187 | other_handshake_key=b_handshake_keys.pub, 188 | priv_ratchet_key=a_ratchet_keys.priv, 189 | ratchet_key=a_ratchet_keys.pub, 190 | other_ratchet_key=b_ratchet_keys.pub) 191 | 192 | ac = axolotl_a.init_conversation( 193 | other_name=axolotl_c.name, 194 | priv_identity_key=a_identity_keys.priv, 195 | identity_key=a_identity_keys.pub, 196 | priv_handshake_key=a_handshake_keys.priv, 197 | other_identity_key=c_identity_keys.pub, 198 | other_handshake_key=c_handshake_keys.pub, 199 | priv_ratchet_key=a_ratchet_keys.priv, 200 | ratchet_key=a_ratchet_keys.pub, 201 | other_ratchet_key=c_ratchet_keys.pub) 202 | 203 | ba = axolotl_b.init_conversation( 204 | other_name=axolotl_a.name, 205 | priv_identity_key=b_identity_keys.priv, 206 | identity_key=b_identity_keys.pub, 207 | priv_handshake_key=b_handshake_keys.priv, 208 | other_identity_key=a_identity_keys.pub, 209 | other_handshake_key=a_handshake_keys.pub, 210 | priv_ratchet_key=b_ratchet_keys.priv, 211 | ratchet_key=b_ratchet_keys.pub, 212 | other_ratchet_key=a_ratchet_keys.pub) 213 | 214 | bc = axolotl_b.init_conversation( 215 | other_name=axolotl_c.name, 216 | priv_identity_key=b_identity_keys.priv, 217 | identity_key=b_identity_keys.pub, 218 | priv_handshake_key=b_handshake_keys.priv, 219 | other_identity_key=c_identity_keys.pub, 220 | other_handshake_key=c_handshake_keys.pub, 221 | priv_ratchet_key=b_ratchet_keys.priv, 222 | ratchet_key=b_ratchet_keys.pub, 223 | other_ratchet_key=c_ratchet_keys.pub) 224 | 225 | ca = axolotl_c.init_conversation( 226 | other_name=axolotl_a.name, 227 | priv_identity_key=c_identity_keys.priv, 228 | identity_key=c_identity_keys.pub, 229 | priv_handshake_key=c_handshake_keys.priv, 230 | other_identity_key=a_identity_keys.pub, 231 | other_handshake_key=a_handshake_keys.pub, 232 | priv_ratchet_key=c_ratchet_keys.priv, 233 | ratchet_key=b_ratchet_keys.pub, 234 | other_ratchet_key=a_ratchet_keys.pub) 235 | 236 | cb = axolotl_c.init_conversation( 237 | other_name=axolotl_b.name, 238 | priv_identity_key=c_identity_keys.priv, 239 | identity_key=c_identity_keys.pub, 240 | priv_handshake_key=c_handshake_keys.priv, 241 | other_identity_key=b_identity_keys.pub, 242 | other_handshake_key=b_handshake_keys.pub, 243 | priv_ratchet_key=c_ratchet_keys.priv, 244 | ratchet_key=c_ratchet_keys.pub, 245 | other_ratchet_key=b_ratchet_keys.pub) 246 | 247 | return Conversations(ab, ac, ba, bc, ca, cb) 248 | 249 | 250 | def create_conversations( 251 | axolotl_a, a_identity_keys, a_handshake_keys, a_ratchet_keys, 252 | axolotl_b, b_identity_keys, b_handshake_keys, b_ratchet_keys, 253 | axolotl_c, c_identity_keys, c_handshake_keys, c_ratchet_keys, 254 | mkey_ab, mkey_ac, mkey_bc): 255 | ab = axolotl_a.create_conversation( 256 | other_name=axolotl_b.name, 257 | mkey=mkey_ab, 258 | mode=True, 259 | priv_identity_key=a_identity_keys.priv, 260 | identity_key=a_identity_keys.pub, 261 | other_identity_key=b_identity_keys.pub, 262 | other_ratchet_key=b_ratchet_keys.pub) 263 | 264 | ac = axolotl_a.create_conversation( 265 | other_name=axolotl_c.name, 266 | mkey=mkey_ac, 267 | mode=False, 268 | priv_identity_key=a_identity_keys.priv, 269 | identity_key=a_identity_keys.pub, 270 | other_identity_key=c_identity_keys.pub, 271 | priv_ratchet_key=a_ratchet_keys.priv, 272 | ratchet_key=a_ratchet_keys.pub) 273 | 274 | ba = axolotl_b.create_conversation( 275 | other_name=axolotl_a.name, 276 | mkey=mkey_ab, 277 | mode=False, 278 | priv_identity_key=b_identity_keys.priv, 279 | identity_key=b_identity_keys.pub, 280 | other_identity_key=a_identity_keys.pub, 281 | priv_ratchet_key=b_ratchet_keys.priv, 282 | ratchet_key=b_ratchet_keys.pub) 283 | 284 | bc = axolotl_b.create_conversation( 285 | other_name=axolotl_c.name, 286 | mkey=mkey_bc, 287 | mode=True, 288 | priv_identity_key=b_identity_keys.priv, 289 | identity_key=b_identity_keys.pub, 290 | other_identity_key=c_identity_keys.pub, 291 | other_ratchet_key=c_ratchet_keys.pub) 292 | 293 | ca = axolotl_c.create_conversation( 294 | other_name=axolotl_a.name, 295 | mkey=mkey_ac, 296 | mode=True, 297 | priv_identity_key=c_identity_keys.priv, 298 | identity_key=c_identity_keys.pub, 299 | other_identity_key=a_identity_keys.pub, 300 | other_ratchet_key=a_ratchet_keys.pub) 301 | 302 | cb = axolotl_c.create_conversation( 303 | other_name=axolotl_b.name, 304 | mkey=mkey_bc, 305 | mode=False, 306 | priv_identity_key=c_identity_keys.priv, 307 | identity_key=c_identity_keys.pub, 308 | other_identity_key=b_identity_keys.pub, 309 | priv_ratchet_key=c_ratchet_keys.priv, 310 | ratchet_key=c_ratchet_keys.pub) 311 | 312 | return Conversations(ab, ac, ba, bc, ca, cb) 313 | 314 | 315 | def run_threaded_exchanges(exchange, conversations): 316 | event = Event() 317 | 318 | queue_ab = Queue() 319 | exchange_ab = ThreadedExchange(exchange, 320 | conversations.ab, conversations.ba, 321 | event, queue_ab) 322 | 323 | queue_ac = Queue() 324 | exchange_ac = ThreadedExchange(exchange, 325 | conversations.ac, conversations.ca, 326 | event, queue_ac) 327 | 328 | queue_bc = Queue() 329 | exchange_bc = ThreadedExchange(exchange, 330 | conversations.bc, conversations.cb, 331 | event, queue_bc) 332 | 333 | exchange_ab.start() 334 | exchange_ac.start() 335 | exchange_bc.start() 336 | 337 | event.set() 338 | 339 | assert queue_ab.get() and queue_ac.get() and queue_bc.get() 340 | -------------------------------------------------------------------------------- /_version.py: -------------------------------------------------------------------------------- 1 | 2 | # This file helps to compute a version number in source trees obtained from 3 | # git-archive tarball (such as those provided by githubs download-from-tag 4 | # feature). Distribution tarballs (built by setup.py sdist) and build 5 | # directories (produced by setup.py build) will contain a much shorter file 6 | # that just contains the computed version number. 7 | 8 | # This file is released into the public domain. Generated by 9 | # versioneer-0.17 (https://github.com/warner/python-versioneer) 10 | 11 | """Git implementation of _version.py.""" 12 | 13 | import errno 14 | import os 15 | import re 16 | import subprocess 17 | import sys 18 | 19 | 20 | def get_keywords(): 21 | """Get the keywords needed to look up the version information.""" 22 | # these strings will be replaced by git during git-archive. 23 | # setup.py/versioneer.py will grep for the variable names, so they must 24 | # each be defined on a line of their own. _version.py will just call 25 | # get_keywords(). 26 | git_refnames = " (HEAD -> master, tag: 0.8.2)" 27 | git_full = "1e34cfa4c4826fb2e024812d1ce71a979d9e0370" 28 | git_date = "2017-09-15 17:11:20 -0500" 29 | keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} 30 | return keywords 31 | 32 | 33 | class VersioneerConfig: 34 | """Container for Versioneer configuration parameters.""" 35 | 36 | 37 | def get_config(): 38 | """Create, populate and return the VersioneerConfig() object.""" 39 | # these strings are filled in when 'setup.py versioneer' creates 40 | # _version.py 41 | cfg = VersioneerConfig() 42 | cfg.VCS = "git" 43 | cfg.style = "" 44 | cfg.tag_prefix = "" 45 | cfg.parentdir_prefix = "" 46 | cfg.versionfile_source = "_version.py" 47 | cfg.verbose = False 48 | return cfg 49 | 50 | 51 | class NotThisMethod(Exception): 52 | """Exception raised if a method is not valid for the current scenario.""" 53 | 54 | 55 | LONG_VERSION_PY = {} 56 | HANDLERS = {} 57 | 58 | 59 | def register_vcs_handler(vcs, method): # decorator 60 | """Decorator to mark a method as the handler for a particular VCS.""" 61 | def decorate(f): 62 | """Store f in HANDLERS[vcs][method].""" 63 | if vcs not in HANDLERS: 64 | HANDLERS[vcs] = {} 65 | HANDLERS[vcs][method] = f 66 | return f 67 | return decorate 68 | 69 | 70 | def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, 71 | env=None): 72 | """Call the given command(s).""" 73 | assert isinstance(commands, list) 74 | p = None 75 | for c in commands: 76 | try: 77 | dispcmd = str([c] + args) 78 | # remember shell=False, so use git.cmd on windows, not just git 79 | p = subprocess.Popen([c] + args, cwd=cwd, env=env, 80 | stdout=subprocess.PIPE, 81 | stderr=(subprocess.PIPE if hide_stderr 82 | else None)) 83 | break 84 | except EnvironmentError: 85 | e = sys.exc_info()[1] 86 | if e.errno == errno.ENOENT: 87 | continue 88 | if verbose: 89 | print("unable to run %s" % dispcmd) 90 | print(e) 91 | return None, None 92 | else: 93 | if verbose: 94 | print("unable to find command, tried %s" % (commands,)) 95 | return None, None 96 | stdout = p.communicate()[0].strip() 97 | if sys.version_info[0] >= 3: 98 | stdout = stdout.decode() 99 | if p.returncode != 0: 100 | if verbose: 101 | print("unable to run %s (error)" % dispcmd) 102 | print("stdout was %s" % stdout) 103 | return None, p.returncode 104 | return stdout, p.returncode 105 | 106 | 107 | def versions_from_parentdir(parentdir_prefix, root, verbose): 108 | """Try to determine the version from the parent directory name. 109 | 110 | Source tarballs conventionally unpack into a directory that includes both 111 | the project name and a version string. We will also support searching up 112 | two directory levels for an appropriately named parent directory 113 | """ 114 | rootdirs = [] 115 | 116 | for i in range(3): 117 | dirname = os.path.basename(root) 118 | if dirname.startswith(parentdir_prefix): 119 | return {"version": dirname[len(parentdir_prefix):], 120 | "full-revisionid": None, 121 | "dirty": False, "error": None, "date": None} 122 | else: 123 | rootdirs.append(root) 124 | root = os.path.dirname(root) # up a level 125 | 126 | if verbose: 127 | print("Tried directories %s but none started with prefix %s" % 128 | (str(rootdirs), parentdir_prefix)) 129 | raise NotThisMethod("rootdir doesn't start with parentdir_prefix") 130 | 131 | 132 | @register_vcs_handler("git", "get_keywords") 133 | def git_get_keywords(versionfile_abs): 134 | """Extract version information from the given file.""" 135 | # the code embedded in _version.py can just fetch the value of these 136 | # keywords. When used from setup.py, we don't want to import _version.py, 137 | # so we do it with a regexp instead. This function is not used from 138 | # _version.py. 139 | keywords = {} 140 | try: 141 | f = open(versionfile_abs, "r") 142 | for line in f.readlines(): 143 | if line.strip().startswith("git_refnames ="): 144 | mo = re.search(r'=\s*"(.*)"', line) 145 | if mo: 146 | keywords["refnames"] = mo.group(1) 147 | if line.strip().startswith("git_full ="): 148 | mo = re.search(r'=\s*"(.*)"', line) 149 | if mo: 150 | keywords["full"] = mo.group(1) 151 | if line.strip().startswith("git_date ="): 152 | mo = re.search(r'=\s*"(.*)"', line) 153 | if mo: 154 | keywords["date"] = mo.group(1) 155 | f.close() 156 | except EnvironmentError: 157 | pass 158 | return keywords 159 | 160 | 161 | @register_vcs_handler("git", "keywords") 162 | def git_versions_from_keywords(keywords, tag_prefix, verbose): 163 | """Get version information from git keywords.""" 164 | if not keywords: 165 | raise NotThisMethod("no keywords at all, weird") 166 | date = keywords.get("date") 167 | if date is not None: 168 | # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant 169 | # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 170 | # -like" string, which we must then edit to make compliant), because 171 | # it's been around since git-1.5.3, and it's too difficult to 172 | # discover which version we're using, or to work around using an 173 | # older one. 174 | date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) 175 | refnames = keywords["refnames"].strip() 176 | if refnames.startswith("$Format"): 177 | if verbose: 178 | print("keywords are unexpanded, not using") 179 | raise NotThisMethod("unexpanded keywords, not a git-archive tarball") 180 | refs = set([r.strip() for r in refnames.strip("()").split(",")]) 181 | # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of 182 | # just "foo-1.0". If we see a "tag: " prefix, prefer those. 183 | TAG = "tag: " 184 | tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) 185 | if not tags: 186 | # Either we're using git < 1.8.3, or there really are no tags. We use 187 | # a heuristic: assume all version tags have a digit. The old git %d 188 | # expansion behaves like git log --decorate=short and strips out the 189 | # refs/heads/ and refs/tags/ prefixes that would let us distinguish 190 | # between branches and tags. By ignoring refnames without digits, we 191 | # filter out many common branch names like "release" and 192 | # "stabilization", as well as "HEAD" and "master". 193 | tags = set([r for r in refs if re.search(r'\d', r)]) 194 | if verbose: 195 | print("discarding '%s', no digits" % ",".join(refs - tags)) 196 | if verbose: 197 | print("likely tags: %s" % ",".join(sorted(tags))) 198 | for ref in sorted(tags): 199 | # sorting will prefer e.g. "2.0" over "2.0rc1" 200 | if ref.startswith(tag_prefix): 201 | r = ref[len(tag_prefix):] 202 | if verbose: 203 | print("picking %s" % r) 204 | return {"version": r, 205 | "full-revisionid": keywords["full"].strip(), 206 | "dirty": False, "error": None, 207 | "date": date} 208 | # no suitable tags, so version is "0+unknown", but full hex is still there 209 | if verbose: 210 | print("no suitable tags, using unknown + full revision id") 211 | return {"version": "0+unknown", 212 | "full-revisionid": keywords["full"].strip(), 213 | "dirty": False, "error": "no suitable tags", "date": None} 214 | 215 | 216 | @register_vcs_handler("git", "pieces_from_vcs") 217 | def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): 218 | """Get version from 'git describe' in the root of the source tree. 219 | 220 | This only gets called if the git-archive 'subst' keywords were *not* 221 | expanded, and _version.py hasn't already been rewritten with a short 222 | version string, meaning we're inside a checked out source tree. 223 | """ 224 | GITS = ["git"] 225 | if sys.platform == "win32": 226 | GITS = ["git.cmd", "git.exe"] 227 | 228 | out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, 229 | hide_stderr=True) 230 | if rc != 0: 231 | if verbose: 232 | print("Directory %s not under git control" % root) 233 | raise NotThisMethod("'git rev-parse --git-dir' returned error") 234 | 235 | # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] 236 | # if there isn't one, this yields HEX[-dirty] (no NUM) 237 | describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", 238 | "--always", "--long", 239 | "--match", "%s*" % tag_prefix], 240 | cwd=root) 241 | # --long was added in git-1.5.5 242 | if describe_out is None: 243 | raise NotThisMethod("'git describe' failed") 244 | describe_out = describe_out.strip() 245 | full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) 246 | if full_out is None: 247 | raise NotThisMethod("'git rev-parse' failed") 248 | full_out = full_out.strip() 249 | 250 | pieces = {} 251 | pieces["long"] = full_out 252 | pieces["short"] = full_out[:7] # maybe improved later 253 | pieces["error"] = None 254 | 255 | # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] 256 | # TAG might have hyphens. 257 | git_describe = describe_out 258 | 259 | # look for -dirty suffix 260 | dirty = git_describe.endswith("-dirty") 261 | pieces["dirty"] = dirty 262 | if dirty: 263 | git_describe = git_describe[:git_describe.rindex("-dirty")] 264 | 265 | # now we have TAG-NUM-gHEX or HEX 266 | 267 | if "-" in git_describe: 268 | # TAG-NUM-gHEX 269 | mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) 270 | if not mo: 271 | # unparseable. Maybe git-describe is misbehaving? 272 | pieces["error"] = ("unable to parse git-describe output: '%s'" 273 | % describe_out) 274 | return pieces 275 | 276 | # tag 277 | full_tag = mo.group(1) 278 | if not full_tag.startswith(tag_prefix): 279 | if verbose: 280 | fmt = "tag '%s' doesn't start with prefix '%s'" 281 | print(fmt % (full_tag, tag_prefix)) 282 | pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" 283 | % (full_tag, tag_prefix)) 284 | return pieces 285 | pieces["closest-tag"] = full_tag[len(tag_prefix):] 286 | 287 | # distance: number of commits since tag 288 | pieces["distance"] = int(mo.group(2)) 289 | 290 | # commit: short hex revision ID 291 | pieces["short"] = mo.group(3) 292 | 293 | else: 294 | # HEX: no tags 295 | pieces["closest-tag"] = None 296 | count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], 297 | cwd=root) 298 | pieces["distance"] = int(count_out) # total number of commits 299 | 300 | # commit date: see ISO-8601 comment in git_versions_from_keywords() 301 | date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], 302 | cwd=root)[0].strip() 303 | pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) 304 | 305 | return pieces 306 | 307 | 308 | def plus_or_dot(pieces): 309 | """Return a + if we don't already have one, else return a .""" 310 | if "+" in pieces.get("closest-tag", ""): 311 | return "." 312 | return "+" 313 | 314 | 315 | def render_pep440(pieces): 316 | """Build up version string, with post-release "local version identifier". 317 | 318 | Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you 319 | get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty 320 | 321 | Exceptions: 322 | 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] 323 | """ 324 | if pieces["closest-tag"]: 325 | rendered = pieces["closest-tag"] 326 | if pieces["distance"] or pieces["dirty"]: 327 | rendered += plus_or_dot(pieces) 328 | rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) 329 | if pieces["dirty"]: 330 | rendered += ".dirty" 331 | else: 332 | # exception #1 333 | rendered = "0+untagged.%d.g%s" % (pieces["distance"], 334 | pieces["short"]) 335 | if pieces["dirty"]: 336 | rendered += ".dirty" 337 | return rendered 338 | 339 | 340 | def render_pep440_pre(pieces): 341 | """TAG[.post.devDISTANCE] -- No -dirty. 342 | 343 | Exceptions: 344 | 1: no tags. 0.post.devDISTANCE 345 | """ 346 | if pieces["closest-tag"]: 347 | rendered = pieces["closest-tag"] 348 | if pieces["distance"]: 349 | rendered += ".post.dev%d" % pieces["distance"] 350 | else: 351 | # exception #1 352 | rendered = "0.post.dev%d" % pieces["distance"] 353 | return rendered 354 | 355 | 356 | def render_pep440_post(pieces): 357 | """TAG[.postDISTANCE[.dev0]+gHEX] . 358 | 359 | The ".dev0" means dirty. Note that .dev0 sorts backwards 360 | (a dirty tree will appear "older" than the corresponding clean one), 361 | but you shouldn't be releasing software with -dirty anyways. 362 | 363 | Exceptions: 364 | 1: no tags. 0.postDISTANCE[.dev0] 365 | """ 366 | if pieces["closest-tag"]: 367 | rendered = pieces["closest-tag"] 368 | if pieces["distance"] or pieces["dirty"]: 369 | rendered += ".post%d" % pieces["distance"] 370 | if pieces["dirty"]: 371 | rendered += ".dev0" 372 | rendered += plus_or_dot(pieces) 373 | rendered += "g%s" % pieces["short"] 374 | else: 375 | # exception #1 376 | rendered = "0.post%d" % pieces["distance"] 377 | if pieces["dirty"]: 378 | rendered += ".dev0" 379 | rendered += "+g%s" % pieces["short"] 380 | return rendered 381 | 382 | 383 | def render_pep440_old(pieces): 384 | """TAG[.postDISTANCE[.dev0]] . 385 | 386 | The ".dev0" means dirty. 387 | 388 | Eexceptions: 389 | 1: no tags. 0.postDISTANCE[.dev0] 390 | """ 391 | if pieces["closest-tag"]: 392 | rendered = pieces["closest-tag"] 393 | if pieces["distance"] or pieces["dirty"]: 394 | rendered += ".post%d" % pieces["distance"] 395 | if pieces["dirty"]: 396 | rendered += ".dev0" 397 | else: 398 | # exception #1 399 | rendered = "0.post%d" % pieces["distance"] 400 | if pieces["dirty"]: 401 | rendered += ".dev0" 402 | return rendered 403 | 404 | 405 | def render_git_describe(pieces): 406 | """TAG[-DISTANCE-gHEX][-dirty]. 407 | 408 | Like 'git describe --tags --dirty --always'. 409 | 410 | Exceptions: 411 | 1: no tags. HEX[-dirty] (note: no 'g' prefix) 412 | """ 413 | if pieces["closest-tag"]: 414 | rendered = pieces["closest-tag"] 415 | if pieces["distance"]: 416 | rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) 417 | else: 418 | # exception #1 419 | rendered = pieces["short"] 420 | if pieces["dirty"]: 421 | rendered += "-dirty" 422 | return rendered 423 | 424 | 425 | def render_git_describe_long(pieces): 426 | """TAG-DISTANCE-gHEX[-dirty]. 427 | 428 | Like 'git describe --tags --dirty --always -long'. 429 | The distance/hash is unconditional. 430 | 431 | Exceptions: 432 | 1: no tags. HEX[-dirty] (note: no 'g' prefix) 433 | """ 434 | if pieces["closest-tag"]: 435 | rendered = pieces["closest-tag"] 436 | rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) 437 | else: 438 | # exception #1 439 | rendered = pieces["short"] 440 | if pieces["dirty"]: 441 | rendered += "-dirty" 442 | return rendered 443 | 444 | 445 | def render(pieces, style): 446 | """Render the given version pieces into the requested style.""" 447 | if pieces["error"]: 448 | return {"version": "unknown", 449 | "full-revisionid": pieces.get("long"), 450 | "dirty": None, 451 | "error": pieces["error"], 452 | "date": None} 453 | 454 | if not style or style == "default": 455 | style = "pep440" # the default 456 | 457 | if style == "pep440": 458 | rendered = render_pep440(pieces) 459 | elif style == "pep440-pre": 460 | rendered = render_pep440_pre(pieces) 461 | elif style == "pep440-post": 462 | rendered = render_pep440_post(pieces) 463 | elif style == "pep440-old": 464 | rendered = render_pep440_old(pieces) 465 | elif style == "git-describe": 466 | rendered = render_git_describe(pieces) 467 | elif style == "git-describe-long": 468 | rendered = render_git_describe_long(pieces) 469 | else: 470 | raise ValueError("unknown style '%s'" % style) 471 | 472 | return {"version": rendered, "full-revisionid": pieces["long"], 473 | "dirty": pieces["dirty"], "error": None, 474 | "date": pieces.get("date")} 475 | 476 | 477 | def get_versions(): 478 | """Get version information or return default if unable to do so.""" 479 | # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have 480 | # __file__, we can work backwards from there to the root. Some 481 | # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which 482 | # case we can only use expanded keywords. 483 | 484 | cfg = get_config() 485 | verbose = cfg.verbose 486 | 487 | try: 488 | return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, 489 | verbose) 490 | except NotThisMethod: 491 | pass 492 | 493 | try: 494 | root = os.path.realpath(__file__) 495 | # versionfile_source is the relative path from the top of the source 496 | # tree (where the .git directory might live) to this file. Invert 497 | # this to find the root from __file__. 498 | for i in cfg.versionfile_source.split('/'): 499 | root = os.path.dirname(root) 500 | except NameError: 501 | return {"version": "0+unknown", "full-revisionid": None, 502 | "dirty": None, 503 | "error": "unable to find root of source tree", 504 | "date": None} 505 | 506 | try: 507 | pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) 508 | return render(pieces, cfg.style) 509 | except NotThisMethod: 510 | pass 511 | 512 | try: 513 | if cfg.parentdir_prefix: 514 | return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) 515 | except NotThisMethod: 516 | pass 517 | 518 | return {"version": "0+unknown", "full-revisionid": None, 519 | "dirty": None, 520 | "error": "unable to compute version", "date": None} 521 | -------------------------------------------------------------------------------- /examples/axotor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import socket 4 | import threading 5 | import sys 6 | import os 7 | import curses 8 | import socks 9 | import stem.process 10 | from wh import WHMgr 11 | import random 12 | from binascii import a2b_base64 as a2b 13 | from binascii import b2a_base64 as b2a 14 | from getpass import getpass 15 | from smp import SMP 16 | from stem.control import Controller 17 | from stem.util import term 18 | from curses.textpad import Textbox 19 | from contextlib import contextmanager 20 | from pyaxo import Axolotl, hash_ 21 | from time import sleep 22 | 23 | """ 24 | Standalone chat script using libsodium for encryption with the Axolotl 25 | ratchet for key management. 26 | 27 | This version of the chat client makes connections over the tor network. 28 | The server creates an ephemeral hidden service and the client connects 29 | to the hidden service. You will need to load the following additional 30 | python modules for this to work: stem, pysocks, txtorcon, pysocks, 31 | and magic-wormhole. They are available on pypi via pip. 32 | 33 | Axotor also requires tor (>=2.9.1). Currently this is in the unstable 34 | branch. So you may need to update your distribution's tor repository 35 | accordingly. 36 | 37 | The only inputs required are the nicks of the conversants, as well as 38 | a master key. The master key must be of the form N-x where N is an 39 | integer (1-3 digits should be fine) and x is a lower-case alphanumeric 40 | string. The initial axolotl database configuration and credential 41 | exchange are derived from the master key. The master key should be 42 | exchanged out-of-band between the two conversants before communication 43 | can be established. An example master key might be 293-xyzzy (don't use 44 | this one). 45 | 46 | On start, the program initializes a tor server and exchanges axolotl 47 | and hidden service authentication credentials over tor using PAKE 48 | (password-authenticated key exchange). The specific implementation of 49 | PAKE used is https://github.com/warner/magic-wormhole. The server 50 | side creates an ephemeral hidden service that requires basic_auth 51 | to connect. 52 | 53 | The hidden service and axolotl credentials are ephemeral. They exist 54 | only in ram, and will be deleted upon exit from the program. Exit by 55 | typing .quit at the chat prompt. 56 | 57 | The client also does an authentication step using the Socialist 58 | Millionaire's Protocol. During startup, after a network connection is 59 | established, you will be prompted for a secret. If the secret 60 | matches that input by the other party, a chat is established and 61 | the input window text appears in green. If the secret does not match 62 | the other party's secret, you will be prompted whether or not to 63 | continue. If you continue, the input window text will appear in red 64 | to remind you that the session is unauthenticated. 65 | 66 | The Axolotl protocol is actually authenticated through the key 67 | agreement process when the credentials are created. You may wonder why 68 | the additional SMP authentication step is included. This SMP step 69 | is another way to assure you that the other party to your session is 70 | actually who you think it is. 71 | 72 | In axotor.py, no database or key is ever stored to disk. 73 | 74 | Usage: 75 | 1. One side starts the server with: 76 | axotor.py -s 77 | 78 | 2. The other side connects the client to the server with: 79 | axotor.py -c 80 | 81 | 3. .quit at the chat prompt will quit (don't forget the "dot") 82 | 83 | 4. .send will send a file to the other party. The file 84 | can be from anywhere in the filesystem on the sending computer 85 | (~/a/b/ supported) and will be stored in the receiver's 86 | local directory. 87 | 88 | Axochat requires the Axolotl module at https://github.com/rxcomm/pyaxo 89 | 90 | Copyright (C) 2015-2017 by David R. Andersen 91 | 92 | This program is free software: you can redistribute it and/or modify 93 | it under the terms of the GNU General Public License as published by 94 | the Free Software Foundation, either version 3 of the License, or 95 | (at your option) any later version. 96 | 97 | This program is distributed in the hope that it will be useful, 98 | but WITHOUT ANY WARRANTY; without even the implied warranty of 99 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 100 | GNU General Public License for more details. 101 | 102 | You should have received a copy of the GNU General Public License 103 | along with this program. If not, see . 104 | """ 105 | 106 | TOR_SERVER_PORT = 9054 107 | TOR_SERVER_CONTROL_PORT = 9055 108 | TOR_CLIENT_PORT = 9154 109 | TOR_CLIENT_CONTROL_PORT = 9155 110 | CLIENT_FILE_TX_PORT = 2000 111 | SERVER_FILE_TX_PORT = 2001 112 | 113 | # An attempt to limit the damage from this bug in curses: 114 | # https://bugs.python.org/issue13051 115 | # The input textbox is 8 rows high. So assuming a maximum 116 | # terminal width of 512 columns, we arrive at 8x512=4096. 117 | # Most terminal windows should be smaller than this. 118 | sys.setrecursionlimit(4096) 119 | 120 | @contextmanager 121 | def socketcontext(*args, **kwargs): 122 | s = socket.socket(*args, **kwargs) 123 | s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 124 | s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) 125 | yield s 126 | s.close() 127 | 128 | @contextmanager 129 | def torcontext(): 130 | try: 131 | s = socks.socksocket() 132 | s.set_proxy(socks.SOCKS5, '127.0.0.1', TOR_CLIENT_PORT) 133 | yield s 134 | s.close() 135 | except socks.SOCKS5Error: 136 | print '' 137 | print 'You need to wait long enough for the Hidden Service' 138 | print 'at the server to be established. Try again in a' 139 | print 'minute or two.' 140 | 141 | class _Textbox(Textbox): 142 | """ 143 | curses.textpad.Textbox requires users to ^g on completion, which is sort 144 | of annoying for an interactive chat client such as this, which typically only 145 | reuquires an enter. This subclass fixes this problem by signalling completion 146 | on Enter as well as ^g. Also, map key to ^h. 147 | """ 148 | def __init__(*args, **kwargs): 149 | Textbox.__init__(*args, **kwargs) 150 | 151 | def do_command(self, ch): 152 | if ch == curses.KEY_RESIZE: 153 | resizeWindows() 154 | for i in range(8): # delete 8 input window lines 155 | Textbox.do_command(self, 1) 156 | Textbox.do_command(self, 11) 157 | Textbox.do_command(self, 16) 158 | return Textbox.do_command(self, 7) 159 | if ch == 10: # Enter 160 | return 0 161 | if ch == 127: # Backspace 162 | return 8 163 | return Textbox.do_command(self, ch) 164 | 165 | def validator(ch): 166 | """ 167 | Update screen if necessary and release the lock so receiveThread can run 168 | """ 169 | global screen_needs_update 170 | try: 171 | if screen_needs_update: 172 | curses.doupdate() 173 | screen_needs_update = False 174 | return ch 175 | finally: 176 | winlock.release() 177 | sleep(0.01) # let receiveThread in if necessary 178 | winlock.acquire() 179 | 180 | def windowFactory(): 181 | stdscr = curses.initscr() 182 | curses.noecho() 183 | curses.start_color() 184 | curses.use_default_colors() 185 | curses.init_pair(1, curses.COLOR_RED, -1) 186 | curses.init_pair(2, curses.COLOR_GREEN, -1) 187 | curses.init_pair(3, curses.COLOR_YELLOW, -1) 188 | curses.cbreak() 189 | curses.curs_set(1) 190 | (sizey, sizex) = stdscr.getmaxyx() 191 | input_win = curses.newwin(8, sizex, sizey-8, 0) 192 | output_win = curses.newwin(sizey-8, sizex, 0, 0) 193 | input_win.idlok(1) 194 | input_win.scrollok(1) 195 | input_win.nodelay(1) 196 | input_win.leaveok(0) 197 | input_win.timeout(100) 198 | output_win.idlok(1) 199 | output_win.scrollok(1) 200 | output_win.leaveok(0) 201 | return stdscr, input_win, output_win 202 | 203 | def closeWindows(stdscr): 204 | curses.nocbreak() 205 | stdscr.keypad(0) 206 | curses.echo() 207 | curses.endwin() 208 | 209 | def resizeWindows(): 210 | global stdscr, input_win, output_win, textpad, text_color 211 | temp_win = output_win 212 | yold, xold = output_win.getmaxyx() 213 | stdscr, input_win, output_win = windowFactory() 214 | stdscr.noutrefresh() 215 | ynew, xnew = output_win.getmaxyx() 216 | if yold > ynew: 217 | sminrow = yold - ynew 218 | dminrow = 0 219 | else: 220 | sminrow = 0 221 | dminrow = ynew - yold 222 | temp_win.overwrite(output_win, sminrow, 0, dminrow, 0, ynew-1, xnew-1) 223 | del temp_win 224 | output_win.move(ynew-1, 0) 225 | output_win.noutrefresh() 226 | input_win.attron(text_color) 227 | input_win.noutrefresh() 228 | curses.doupdate() 229 | textpad = _Textbox(input_win, insert_mode=True) 230 | textpad.stripspaces = True 231 | 232 | def usage(): 233 | print 'Usage: ' + sys.argv[0] + ' -(s,c)' 234 | print ' -s: start a chat in server mode' 235 | print ' -c: start a chat in client mode' 236 | print 'quit with .quit' 237 | print 'send file with .send ' 238 | sys.exit(1) 239 | 240 | def reportTransferSocketError(): 241 | global output_win 242 | with winlock: 243 | output_win.addstr('Socket error: Something went wrong.\n', 244 | curses.color_pair(1)) 245 | output_win.refresh() 246 | sys.exit() 247 | 248 | def sendFile(s, filename, abort): 249 | global axolotl, output_win 250 | if abort: 251 | with cryptlock: 252 | data = axolotl.encrypt('ABORT') + 'EOP' 253 | s.send(data) 254 | try: 255 | s.recv(3, socket.MSG_WAITALL) 256 | except socket.error: 257 | pass 258 | sys.exit() 259 | else: 260 | with winlock: 261 | output_win.addstr('Sending file %s...\n' % filename, 262 | curses.color_pair(3)) 263 | output_win.refresh() 264 | with open(filename, 'rb') as f: 265 | data = f.read() 266 | if len(data) == 0: 267 | data = 'Sender tried to send a null file!' 268 | with cryptlock: 269 | data = axolotl.encrypt(data) 270 | s.send(data + 'EOP') 271 | try: 272 | s.recv(3, socket.MSG_WAITALL) 273 | except socket.error: 274 | pass 275 | 276 | def receiveFile(s, filename): 277 | global axolotl, output_win 278 | data = '' 279 | while data[-3:] != 'EOP': 280 | rcv = s.recv(4096) 281 | data = data + rcv 282 | if not rcv: 283 | with winlock: 284 | output_win.addstr('Receiving %s aborted...\n' % filename, 285 | curses.color_pair(1)) 286 | output_win.refresh() 287 | try: 288 | s.send('EOP') 289 | except socket.error: 290 | pass 291 | sys.exit() 292 | with cryptlock: 293 | data = axolotl.decrypt(data[:-3]) 294 | if data == 'ABORT': 295 | with winlock: 296 | output_win.addstr('Receiving %s aborted...\n' % filename, 297 | curses.color_pair(1)) 298 | output_win.refresh() 299 | sys.exit() 300 | with open(filename, 'wb') as f: 301 | f.write(data) 302 | try: 303 | s.send('EOP') 304 | except socket.error: 305 | pass 306 | 307 | def uploadThread(onion, command): 308 | global output_win 309 | with transferlock: 310 | filename = command.split(':> .send ')[1].strip() 311 | filename = os.path.expanduser(filename) 312 | if not os.path.exists(filename) or os.path.isdir(filename): 313 | with winlock: 314 | output_win.addstr('File %s does not exist...\n' % filename, 315 | curses.color_pair(1)) 316 | output_win.refresh() 317 | abort = True 318 | else: 319 | abort = False 320 | if onion is None: 321 | with socketcontext(socket.AF_INET, socket.SOCK_STREAM) as s: 322 | try: 323 | s.bind(('localhost', SERVER_FILE_TX_PORT)) 324 | s.listen(1) 325 | conn, addr = s.accept() 326 | except socket.error: 327 | reportTransferSocketError() 328 | sendFile(conn, filename, abort) 329 | else: 330 | with torcontext() as s: 331 | try: 332 | s.connect((onion, CLIENT_FILE_TX_PORT)) 333 | except socket.error: 334 | reportTransferSocketError() 335 | sendFile(s, filename, abort) 336 | with winlock: 337 | output_win.addstr('%s sent...\n' % filename, curses.color_pair(3)) 338 | output_win.refresh() 339 | 340 | def downloadThread(onion, command): 341 | global output_win 342 | with transferlock: 343 | filename = command.split(':> .send ')[1].strip().split('/').pop() 344 | with winlock: 345 | output_win.addstr('Receiving file %s...\n' % filename, 346 | curses.color_pair(3)) 347 | output_win.refresh() 348 | if onion is None: 349 | with socketcontext(socket.AF_INET, socket.SOCK_STREAM) as s: 350 | try: 351 | s.bind(('localhost', CLIENT_FILE_TX_PORT)) 352 | s.listen(1) 353 | conn, addr = s.accept() 354 | except socket.error: 355 | reportTransferSocketError() 356 | receiveFile(conn, filename) 357 | else: 358 | with torcontext() as s: 359 | try: 360 | s.connect((onion, SERVER_FILE_TX_PORT)) 361 | except socket.error: 362 | reportTransferSocketError() 363 | receiveFile(s, filename) 364 | with winlock: 365 | output_win.addstr('%s received...\n' % filename, curses.color_pair(3)) 366 | output_win.refresh() 367 | 368 | def receiveThread(sock, text_color, onion): 369 | global screen_needs_update, a, stdscr, input_win, output_win 370 | while True: 371 | data = '' 372 | while data[-3:] != 'EOP': 373 | rcv = sock.recv(1024) 374 | if not rcv: 375 | input_win.move(0, 0) 376 | input_win.addstr('Disconnected - Ctrl-C to exit!', 377 | text_color) 378 | input_win.refresh() 379 | sys.exit() 380 | data = data + rcv 381 | data_list = data.split('EOP') 382 | with winlock: 383 | (cursory, cursorx) = input_win.getyx() 384 | for data in data_list: 385 | if data != '': 386 | with cryptlock: 387 | data = axolotl.decrypt(data) 388 | if ':> .quit' in data: 389 | closeWindows(stdscr) 390 | print 'The other party exited the chat...' 391 | sleep(1.5) 392 | os._exit(0) 393 | if ':> .send ' in data: 394 | t = threading.Thread(target=downloadThread, 395 | args=(onion,data)) 396 | t.start() 397 | data = '' 398 | output_win.addstr(data) 399 | input_win.move(cursory, cursorx) 400 | input_win.cursyncup() 401 | input_win.noutrefresh() 402 | output_win.noutrefresh() 403 | screen_needs_update = True 404 | 405 | def chatThread(sock, smp_match, onion): 406 | global screen_needs_update, axolotl, stdscr, input_win, \ 407 | output_win, textpad, text_color 408 | stdscr, input_win, output_win = windowFactory() 409 | y, x = output_win.getmaxyx() 410 | output_win.move(y-1, 0) 411 | if smp_match: 412 | text_color = curses.color_pair(2) # green 413 | else: 414 | text_color = curses.color_pair(1) # red 415 | input_win.attron(text_color) 416 | input_win.addstr(0, 0, NICK + ':> ') 417 | textpad = _Textbox(input_win, insert_mode=True) 418 | textpad.stripspaces = True 419 | t = threading.Thread(target=receiveThread, 420 | args=(sock, text_color, onion)) 421 | t.daemon = True 422 | t.start() 423 | try: 424 | while True: 425 | with winlock: 426 | data = textpad.edit(validator) 427 | if len(data) != 0 and chr(127) not in data: 428 | input_win.clear() 429 | input_win.addstr(NICK+':> ') 430 | output_win.addstr(data.replace('\n', '') + '\n', text_color) 431 | output_win.noutrefresh() 432 | input_win.move(0, len(NICK)+3) 433 | input_win.cursyncup() 434 | input_win.noutrefresh() 435 | screen_needs_update = True 436 | data = data.replace('\n', '') + '\n' 437 | try: 438 | with cryptlock: 439 | sock.send(axolotl.encrypt(data) + 'EOP') 440 | except socket.error: 441 | input_win.addstr('Disconnected') 442 | input_win.refresh() 443 | closeWindows(stdscr) 444 | sys.exit() 445 | if NICK+':> .quit' in data: 446 | closeWindows(stdscr) 447 | print 'Notifying the other party that you are quitting...' 448 | sys.exit() 449 | elif NICK+':> .send ' in data: 450 | t = threading.Thread(target=uploadThread, 451 | args=(onion,data)) 452 | t.start() 453 | else: 454 | input_win.addstr(NICK+':> ') 455 | input_win.move(0, len(NICK)+3) 456 | input_win.cursyncup() 457 | input_win.noutrefresh() 458 | screen_needs_update = True 459 | if screen_needs_update: 460 | curses.doupdate() 461 | screen_needs_update = False 462 | except KeyboardInterrupt: 463 | closeWindows(stdscr) 464 | 465 | def tor(port, controlport, tor_dir, descriptor_cookie): 466 | tor_process = stem.process.launch_tor_with_config( 467 | tor_cmd = 'tor', 468 | config = { 469 | 'ControlPort': str(controlport), 470 | 'SocksPort' : str(port), 471 | 'Log' : [ 'NOTICE stdout', 'ERR file /tmp/tor_error_log', ], 472 | 'DataDirectory' : tor_dir, 473 | 'CookieAuthentication': '1', 474 | 'HidServAuth': descriptor_cookie, 475 | }, 476 | completion_percent = 100, 477 | take_ownership = True, 478 | timeout = 90, 479 | init_msg_handler = print_bootstrap_lines, 480 | ) 481 | return tor_process 482 | 483 | def print_bootstrap_lines(line): 484 | if 'Bootstrapped ' in line: 485 | print(term.format(line, term.Color.RED)) 486 | 487 | def clientController(descriptor_cookie, onion): 488 | controller = Controller.from_port(address='127.0.0.1', 489 | port=TOR_CLIENT_CONTROL_PORT) 490 | try: 491 | controller.authenticate() 492 | controller.set_options([ 493 | ('HidServAuth', onion + ' ' + descriptor_cookie), 494 | ]) 495 | except Exception as e: 496 | print e 497 | return controller 498 | 499 | def ephemeralHiddenService(): 500 | PORT = 50000 501 | HOST = '127.0.0.1' 502 | print 'Waiting for Hidden Service descriptor to be published...' 503 | print ' (this may take some time)' 504 | 505 | controller = Controller.from_port(address='127.0.0.1', 506 | port=TOR_SERVER_CONTROL_PORT) 507 | controller.authenticate() 508 | try: 509 | hs = controller.create_ephemeral_hidden_service([PORT, 510 | CLIENT_FILE_TX_PORT, 511 | SERVER_FILE_TX_PORT], 512 | basic_auth={'axotor': None}, 513 | await_publication=True) 514 | except Exception as e: 515 | print e 516 | return controller, hs.client_auth['axotor'], hs.service_id +'.onion' 517 | 518 | def credentialsSend(mkey, cookie, ratchet_key, onion): 519 | w = WHMgr(unicode(mkey), 520 | cookie+'___'+ratchet_key+'___'+onion, 521 | u'tcp:127.0.0.1:'+unicode(TOR_SERVER_CONTROL_PORT)) 522 | w.send() 523 | w.run() 524 | return w.confirmed 525 | 526 | def credentialsReceive(mkey): 527 | w = WHMgr(unicode(mkey), None, u'tcp:127.0.0.1:'+unicode(TOR_CLIENT_CONTROL_PORT)) 528 | w.receive() 529 | w.run() 530 | return w.data 531 | 532 | def smptest(secret, sock, is_server): 533 | global axolotl 534 | # Create an SMP object with the calculated secret 535 | smp = SMP(secret) 536 | 537 | if is_server: 538 | # Do the SMP protocol 539 | buffer = sock.recv(2439, socket.MSG_WAITALL) 540 | padlength = ord(buffer[-1:]) 541 | buffer = axolotl.decrypt(buffer[:-padlength]) 542 | buffer = smp.step2(buffer) 543 | buffer = axolotl.encrypt(buffer) 544 | padlength = 4539-len(buffer) 545 | buffer = buffer+padlength*chr(padlength) # pad to fixed length 546 | sock.send(buffer) 547 | 548 | buffer = sock.recv(3469, socket.MSG_WAITALL) 549 | padlength = ord(buffer[-1:]) 550 | buffer = axolotl.decrypt(buffer[:-padlength]) 551 | buffer = smp.step4(buffer) 552 | buffer = axolotl.encrypt(buffer) 553 | padlength = 1369-len(buffer) 554 | buffer = buffer+padlength*chr(padlength) # pad to fixed length 555 | sock.send(buffer) 556 | 557 | else: 558 | # Do the SMP protocol 559 | buffer = smp.step1() 560 | buffer = axolotl.encrypt(buffer) 561 | padlength = 2439-len(buffer) 562 | buffer = buffer+padlength*chr(padlength) # pad to fixed length 563 | sock.send(buffer) 564 | 565 | buffer = sock.recv(4539, socket.MSG_WAITALL) 566 | padlength = ord(buffer[-1:]) 567 | buffer = axolotl.decrypt(buffer[:-padlength]) 568 | buffer = smp.step3(buffer) 569 | buffer = axolotl.encrypt(buffer) 570 | padlength = 3469-len(buffer) 571 | buffer = buffer+padlength*chr(padlength) # pad to fixed length 572 | sock.send(buffer) 573 | 574 | buffer = sock.recv(1369, socket.MSG_WAITALL) 575 | padlength = ord(buffer[-1:]) 576 | buffer = axolotl.decrypt(buffer[:-padlength]) 577 | smp.step5(buffer) 578 | 579 | # Check if the secrets match 580 | if smp.match: 581 | print 'Secrets Match!' 582 | sleep(1) 583 | smp_match = True 584 | else: 585 | print 'Secrets DO NOT Match!' 586 | smp_match = False 587 | return smp_match 588 | 589 | def doSMP(sock, is_server): 590 | global axolotl 591 | ans = raw_input('Run SMP authentication step? (y/N)? ') 592 | if not ans == 'y': ans = 'N' 593 | sock.send(axolotl.encrypt(ans)) 594 | data = sock.recv(125, socket.MSG_WAITALL) 595 | data = axolotl.decrypt(data) 596 | if ans == 'N' and data == 'y': 597 | print 'Other party requested SMP authentication' 598 | if ans == 'y' or data == 'y': 599 | print 'Performing per-session SMP authentication...' 600 | ans = getpass('Enter SMP secret: ') 601 | print 'Running SMP protocol...' 602 | secret = ans + axolotl.state['CONVid'] 603 | smp_match = smptest(secret, sock, is_server) 604 | if not smp_match: 605 | ans = raw_input('Continue? (y/N) ') 606 | if ans != 'y': 607 | print 'Exiting...' 608 | sys.exit() 609 | else: 610 | print 'OK - skipping SMP step and assuming ' + \ 611 | 'the other party is already authenticated...' 612 | smp_match = True 613 | sleep(2) 614 | return smp_match 615 | 616 | if __name__ == '__main__': 617 | global axolotl 618 | try: 619 | mode = sys.argv[1] 620 | except: 621 | usage() 622 | 623 | NICK = raw_input('Enter your nick: ') 624 | OTHER_NICK = 'x' 625 | winlock = threading.Lock() 626 | transferlock = threading.Lock() 627 | cryptlock = threading.Lock() 628 | screen_needs_update = False 629 | HOST = '127.0.0.1' 630 | PORT=50000 631 | mkey = getpass('What is the masterkey (format: NNN-xxxx)? ') 632 | 633 | if mode == '-s': 634 | axolotl = Axolotl(NICK, 635 | dbname=OTHER_NICK+'.db', 636 | dbpassphrase=None, 637 | nonthreaded_sql=False) 638 | axolotl.createState(other_name=OTHER_NICK, 639 | mkey=hash_(mkey), 640 | mode=False) 641 | tor_process = tor(TOR_SERVER_PORT, 642 | TOR_SERVER_CONTROL_PORT, 643 | '/tmp/tor.server', 644 | '') 645 | hs, cookie, onion = ephemeralHiddenService() 646 | print 'Exchanging credentials via tor...' 647 | if credentialsSend(mkey, 648 | cookie, 649 | b2a(axolotl.state['DHRs']).strip(), 650 | onion): 651 | pass 652 | else: 653 | sys.exit(1) 654 | print 'Credentials sent, waiting for the other party to connect...' 655 | with socketcontext(socket.AF_INET, socket.SOCK_STREAM) as s: 656 | s.bind((HOST, PORT)) 657 | s.listen(1) 658 | conn, addr = s.accept() 659 | print 'Connected...' 660 | smp_match = doSMP(conn, True) 661 | chatThread(conn, smp_match, None) 662 | 663 | elif mode == '-c': 664 | axolotl = Axolotl(NICK, 665 | dbname=OTHER_NICK+'.db', 666 | dbpassphrase=None, 667 | nonthreaded_sql=False) 668 | tor_process = tor(TOR_CLIENT_PORT, 669 | TOR_CLIENT_CONTROL_PORT, 670 | '/tmp/tor.client', 671 | '') 672 | print 'Exchanging credentials via tor...' 673 | creds = credentialsReceive(mkey) 674 | if not creds: 675 | print 'Master Key Mismatch!' 676 | print 'Exiting...' 677 | sys.exit() 678 | cookie, rkey, onion = creds.split('___') 679 | controller = clientController(cookie, onion) 680 | axolotl.createState(other_name=OTHER_NICK, 681 | mkey=hash_(mkey), 682 | mode=True, 683 | other_ratchetKey=a2b(rkey)) 684 | 685 | print 'Credentials received, connecting to the other party...' 686 | with torcontext() as s: 687 | s.connect((onion, PORT)) 688 | print 'Connected...' 689 | smp_match = doSMP(s, False) 690 | chatThread(s, smp_match, onion) 691 | 692 | else: 693 | usage() 694 | -------------------------------------------------------------------------------- /pyaxo.py: -------------------------------------------------------------------------------- 1 | """ 2 | pyaxo.py - a python implementation of the axolotl ratchet protocol. 3 | https://github.com/trevp/axolotl/wiki/newversion 4 | 5 | Symmetric encryption is done using the python-gnupg module. 6 | 7 | Copyright (C) 2014 by David R. Andersen 8 | 9 | This program is free software: you can redistribute it and/or modify 10 | it under the terms of the GNU General Public License as published by 11 | the Free Software Foundation, either version 3 of the License, or 12 | (at your option) any later version. 13 | 14 | This program is distributed in the hope that it will be useful, 15 | but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | GNU General Public License for more details. 18 | 19 | You should have received a copy of the GNU General Public License 20 | along with this program. If not, see . 21 | 22 | For more information, see https://github.com/rxcomm/pyaxo 23 | """ 24 | 25 | import errno 26 | import os 27 | import sqlite3 28 | import sys 29 | import struct 30 | from collections import namedtuple 31 | from functools import wraps 32 | from getpass import getpass 33 | from threading import Lock 34 | from time import time 35 | 36 | import nacl.secret 37 | import nacl.utils 38 | from nacl.encoding import Base64Encoder 39 | from nacl.exceptions import CryptoError 40 | from nacl.hash import sha256 41 | from nacl.public import PrivateKey, PublicKey, Box 42 | from passlib.utils.pbkdf2 import pbkdf2 43 | 44 | 45 | ALICE_MODE = True 46 | BOB_MODE = False 47 | 48 | SALTS = {'RK': b'\x00', 49 | 'HK': {ALICE_MODE: b'\x01', BOB_MODE: b'\x02'}, 50 | 'NHK': {ALICE_MODE: b'\x03', BOB_MODE: b'\x04'}, 51 | 'CK': {ALICE_MODE: b'\x05', BOB_MODE: b'\x06'}, 52 | 'CONVid': b'\x07'} 53 | 54 | HEADER_LEN = 84 55 | HEADER_PAD_NUM_LEN = 1 56 | HEADER_COUNT_NUM_LEN = 4 57 | 58 | 59 | def sync(f): 60 | @wraps(f) 61 | def synced_f(self, *args, **kwargs): 62 | with self.lock: 63 | return f(self, *args, **kwargs) 64 | return synced_f 65 | 66 | 67 | class Axolotl(object): 68 | 69 | def __init__(self, name, dbname='axolotl.db', dbpassphrase='', nonthreaded_sql=True): 70 | self.name = name 71 | self.dbname = dbname 72 | self.nonthreaded_sql = nonthreaded_sql 73 | if dbpassphrase is None: 74 | self.dbpassphrase = None 75 | elif dbpassphrase != '': 76 | self.dbpassphrase = hash_(dbpassphrase) 77 | else: 78 | self.dbpassphrase = getpass('Database passphrase for '+ self.name + ': ').strip() 79 | self.conversation = AxolotlConversation(self, keys=dict(), mode=None) 80 | self.state['DHIs_priv'], self.state['DHIs'] = generate_keypair() 81 | self.state['DHRs_priv'], self.state['DHRs'] = generate_keypair() 82 | self.handshakeKey, self.handshakePKey = generate_keypair() 83 | self.storeTime = 2*86400 # minimum time (seconds) to store missed ephemeral message keys 84 | self.persistence = SqlitePersistence(self.dbname, 85 | self.dbpassphrase, 86 | self.storeTime, 87 | self.nonthreaded_sql) 88 | 89 | @property 90 | def state(self): 91 | return self.conversation.keys 92 | 93 | @state.setter 94 | def state(self, state): 95 | self.conversation.keys = state 96 | 97 | @property 98 | def mode(self): 99 | return self.conversation.mode 100 | 101 | @mode.setter 102 | def mode(self, mode): 103 | self.conversation.mode = mode 104 | 105 | @property 106 | def db(self): 107 | return self.persistence.db 108 | 109 | @db.setter 110 | def db(self, db): 111 | self.persistence.db = db 112 | 113 | def tripleDH(self, a, a0, B, B0): 114 | if self.mode == None: 115 | sys.exit(1) 116 | return generate_3dh(a, a0, B, B0, self.mode) 117 | 118 | def genDH(self, a, B): 119 | return generate_dh(a, B) 120 | 121 | def genKey(self): 122 | return generate_keypair() 123 | 124 | def initState(self, other_name, other_identityKey, other_handshakeKey, 125 | other_ratchetKey, verify=True): 126 | if verify: 127 | print 'Confirm ' + other_name + ' has identity key fingerprint:\n' 128 | fingerprint = hash_(other_identityKey).encode('hex').upper() 129 | fprint = '' 130 | for i in range(0, len(fingerprint), 4): 131 | fprint += fingerprint[i:i+2] + ':' 132 | print fprint[:-1] + '\n' 133 | print 'Be sure to verify this fingerprint with ' + other_name + \ 134 | ' by some out-of-band method!' 135 | print 'Otherwise, you may be subject to a Man-in-the-middle attack!\n' 136 | ans = raw_input('Confirm? y/N: ').strip() 137 | if ans != 'y': 138 | print 'Key fingerprint not confirmed - exiting...' 139 | sys.exit() 140 | 141 | self.conversation = self.init_conversation(other_name, 142 | self.state['DHIs_priv'], 143 | self.state['DHIs'], 144 | self.handshakeKey, 145 | other_identityKey, 146 | other_handshakeKey, 147 | self.state['DHRs_priv'], 148 | self.state['DHRs'], 149 | other_ratchetKey) 150 | 151 | def init_conversation(self, other_name, 152 | priv_identity_key, identity_key, priv_handshake_key, 153 | other_identity_key, other_handshake_key, 154 | priv_ratchet_key=None, ratchet_key=None, 155 | other_ratchet_key=None, mode=None): 156 | if mode is None: 157 | if identity_key < other_identity_key: 158 | mode = ALICE_MODE 159 | else: 160 | mode = BOB_MODE 161 | 162 | mkey = generate_3dh(priv_identity_key, priv_handshake_key, 163 | other_identity_key, other_handshake_key, 164 | mode) 165 | 166 | return self.create_conversation(other_name, 167 | mkey, 168 | mode, 169 | priv_identity_key, 170 | identity_key, 171 | other_identity_key, 172 | priv_ratchet_key, 173 | ratchet_key, 174 | other_ratchet_key) 175 | 176 | def createState(self, other_name, mkey, mode=None, other_identityKey=None, other_ratchetKey=None): 177 | if mode is not None: 178 | self.mode = mode 179 | else: 180 | if self.mode is None: # mode not selected 181 | sys.exit(1) 182 | 183 | self.conversation = self.create_conversation(other_name, 184 | mkey, 185 | self.mode, 186 | self.state['DHIs_priv'], 187 | self.state['DHIs'], 188 | other_identityKey, 189 | self.state['DHRs_priv'], 190 | self.state['DHRs'], 191 | other_ratchetKey) 192 | 193 | self.ratchetKey = False 194 | self.ratchetPKey = False 195 | 196 | def create_conversation(self, other_name, mkey, mode, 197 | priv_identity_key, identity_key, 198 | other_identity_key, 199 | priv_ratchet_key=None, ratchet_key=None, 200 | other_ratchet_key=None): 201 | if mode is ALICE_MODE: 202 | HKs = None 203 | HKr = kdf(mkey, SALTS['HK'][BOB_MODE]) 204 | CKs = None 205 | CKr = kdf(mkey, SALTS['CK'][BOB_MODE]) 206 | DHRs_priv = None 207 | DHRs = None 208 | DHRr = other_ratchet_key 209 | Ns = 0 210 | Nr = 0 211 | PNs = 0 212 | ratchet_flag = True 213 | else: # bob mode 214 | HKs = kdf(mkey, SALTS['HK'][BOB_MODE]) 215 | HKr = None 216 | CKs = kdf(mkey, SALTS['CK'][BOB_MODE]) 217 | CKr = None 218 | DHRs_priv = priv_ratchet_key 219 | DHRs = ratchet_key 220 | DHRr = None 221 | Ns = 0 222 | Nr = 0 223 | PNs = 0 224 | ratchet_flag = False 225 | RK = kdf(mkey, SALTS['RK']) 226 | NHKs = kdf(mkey, SALTS['NHK'][mode]) 227 | NHKr = kdf(mkey, SALTS['NHK'][not mode]) 228 | CONVid = kdf(mkey, SALTS['CONVid']) 229 | DHIr = other_identity_key 230 | 231 | keys = \ 232 | { 'name': self.name, 233 | 'other_name': other_name, 234 | 'RK': RK, 235 | 'HKs': HKs, 236 | 'HKr': HKr, 237 | 'NHKs': NHKs, 238 | 'NHKr': NHKr, 239 | 'CKs': CKs, 240 | 'CKr': CKr, 241 | 'DHIs_priv': priv_identity_key, 242 | 'DHIs': identity_key, 243 | 'DHIr': DHIr, 244 | 'DHRs_priv': DHRs_priv, 245 | 'DHRs': DHRs, 246 | 'DHRr': DHRr, 247 | 'CONVid': CONVid, 248 | 'Ns': Ns, 249 | 'Nr': Nr, 250 | 'PNs': PNs, 251 | 'ratchet_flag': ratchet_flag, 252 | } 253 | 254 | return AxolotlConversation(self, keys, mode) 255 | 256 | def encrypt(self, plaintext): 257 | return self.conversation.encrypt(plaintext) 258 | 259 | def enc(self, key, plaintext): 260 | return encrypt_symmetric(key, plaintext) 261 | 262 | def dec(self, key, encrypted): 263 | return decrypt_symmetric(key, encrypted) 264 | 265 | def decrypt(self, msg): 266 | return self.conversation.decrypt(msg) 267 | 268 | def encrypt_file(self, filename): 269 | self.conversation.encrypt_file(filename) 270 | 271 | def decrypt_file(self, filename): 272 | self.conversation.decrypt_file(filename) 273 | 274 | def encrypt_pipe(self): 275 | self.conversation.encrypt_pipe() 276 | 277 | def decrypt_pipe(self): 278 | self.conversation.decrypt_pipe() 279 | 280 | def printKeys(self): 281 | self.conversation.print_keys() 282 | 283 | def saveState(self): 284 | self.save_conversation(self.conversation) 285 | 286 | def save_conversation(self, conversation): 287 | self.persistence.save_conversation(conversation) 288 | 289 | def loadState(self, name, other_name): 290 | self.persistence.db = self.openDB() 291 | self.conversation = self.load_conversation(other_name, name) 292 | if self.conversation: 293 | return 294 | else: 295 | return False 296 | 297 | def load_conversation(self, other_name, name=None): 298 | return self.persistence.load_conversation(self, 299 | name or self.name, 300 | other_name) 301 | 302 | def delete_conversation(self, conversation): 303 | return self.persistence.delete_conversation(conversation) 304 | 305 | def get_other_names(self): 306 | return self.persistence.get_other_names(self.name) 307 | 308 | def openDB(self): 309 | return self.persistence._open_db() 310 | 311 | def writeDB(self): 312 | self.persistence.write_db() 313 | 314 | def printState(self): 315 | self.conversation.print_state() 316 | 317 | 318 | class AxolotlConversation: 319 | def __init__(self, axolotl, keys, mode, staged_hk_mk=None): 320 | self._axolotl = axolotl 321 | self.lock = Lock() 322 | self.keys = keys 323 | self.mode = mode 324 | self.staged_hk_mk = staged_hk_mk or dict() 325 | self.staged = False 326 | 327 | self.handshake_key = None 328 | self.handshake_pkey = None 329 | 330 | @property 331 | def name(self): 332 | return self.keys['name'] 333 | 334 | @name.setter 335 | def name(self, name): 336 | self.keys['name'] = name 337 | 338 | @property 339 | def other_name(self): 340 | return self.keys['other_name'] 341 | 342 | @other_name.setter 343 | def other_name(self, other_name): 344 | self.keys['other_name'] = other_name 345 | 346 | @property 347 | def id_(self): 348 | return self.keys['CONVid'] 349 | 350 | @id_.setter 351 | def id_(self, id_): 352 | self.keys['CONVid'] = id_ 353 | 354 | @property 355 | def ns(self): 356 | return self.keys['Ns'] 357 | 358 | @ns.setter 359 | def ns(self, ns): 360 | self.keys['Ns'] = ns 361 | 362 | @property 363 | def nr(self): 364 | return self.keys['Nr'] 365 | 366 | @nr.setter 367 | def nr(self, nr): 368 | self.keys['Nr'] = nr 369 | 370 | @property 371 | def pns(self): 372 | return self.keys['PNs'] 373 | 374 | @pns.setter 375 | def pns(self, pns): 376 | self.keys['PNs'] = pns 377 | 378 | @property 379 | def ratchet_flag(self): 380 | return self.keys['ratchet_flag'] 381 | 382 | @ratchet_flag.setter 383 | def ratchet_flag(self, ratchet_flag): 384 | self.keys['ratchet_flag'] = ratchet_flag 385 | 386 | def _try_skipped_mk(self, msg, pad_length): 387 | msg1 = msg[:HEADER_LEN-pad_length] 388 | msg2 = msg[HEADER_LEN:] 389 | for skipped_mk in self.staged_hk_mk.values(): 390 | try: 391 | decrypt_symmetric(skipped_mk.hk, msg1) 392 | body = decrypt_symmetric(skipped_mk.mk, msg2) 393 | except CryptoError: 394 | pass 395 | else: 396 | del self.staged_hk_mk[skipped_mk.mk] 397 | return body 398 | return None 399 | 400 | def _stage_skipped_mk(self, hkr, nr, np, ckr): 401 | timestamp = int(time()) 402 | ckp = ckr 403 | for i in range(np - nr): 404 | mk = hash_(ckp + '0') 405 | ckp = hash_(ckp + '1') 406 | self.staged_hk_mk[mk] = SkippedMessageKey(mk, hkr, timestamp) 407 | self.staged = True 408 | mk = hash_(ckp + '0') 409 | ckp = hash_(ckp + '1') 410 | return ckp, mk 411 | 412 | @sync 413 | def encrypt(self, plaintext): 414 | if self.ratchet_flag: 415 | self.keys['DHRs_priv'], self.keys['DHRs'] = generate_keypair() 416 | self.keys['HKs'] = self.keys['NHKs'] 417 | self.keys['RK'] = hash_(self.keys['RK'] + 418 | generate_dh(self.keys['DHRs_priv'], self.keys['DHRr'])) 419 | self.keys['NHKs'] = kdf(self.keys['RK'], SALTS['NHK'][self.mode]) 420 | self.keys['CKs'] = kdf(self.keys['RK'], SALTS['CK'][self.mode]) 421 | self.pns = self.ns 422 | self.ns = 0 423 | self.ratchet_flag = False 424 | mk = hash_(self.keys['CKs'] + '0') 425 | msg1 = encrypt_symmetric( 426 | self.keys['HKs'], 427 | struct.pack('>I', self.ns) + struct.pack('>I', self.pns) + 428 | self.keys['DHRs']) 429 | msg2 = encrypt_symmetric(mk, plaintext) 430 | pad_length = HEADER_LEN - len(msg1) 431 | pad = os.urandom(pad_length - HEADER_PAD_NUM_LEN) + chr(pad_length) 432 | msg = msg1 + pad + msg2 433 | self.ns += 1 434 | self.keys['CKs'] = hash_(self.keys['CKs'] + '1') 435 | return msg 436 | 437 | @sync 438 | def decrypt(self, msg): 439 | pad = msg[HEADER_LEN-HEADER_PAD_NUM_LEN:HEADER_LEN] 440 | pad_length = ord(pad) 441 | msg1 = msg[:HEADER_LEN-pad_length] 442 | 443 | body = self._try_skipped_mk(msg, pad_length) 444 | if body and body != '': 445 | return body 446 | 447 | header = None 448 | if self.keys['HKr']: 449 | try: 450 | header = decrypt_symmetric(self.keys['HKr'], msg1) 451 | except CryptoError: 452 | pass 453 | if header and header != '': 454 | Np = struct.unpack('>I', header[:HEADER_COUNT_NUM_LEN])[0] 455 | CKp, mk = self._stage_skipped_mk(self.keys['HKr'], self.nr, Np, self.keys['CKr']) 456 | try: 457 | body = decrypt_symmetric(mk, msg[HEADER_LEN:]) 458 | except CryptoError: 459 | print 'Undecipherable message' 460 | sys.exit(1) 461 | else: 462 | try: 463 | header = decrypt_symmetric(self.keys['NHKr'], msg1) 464 | except CryptoError: 465 | pass 466 | if self.ratchet_flag or not header or header == '': 467 | print 'Undecipherable message' 468 | sys.exit(1) 469 | Np = struct.unpack('>I', header[:HEADER_COUNT_NUM_LEN])[0] 470 | PNp = struct.unpack('>I', header[HEADER_COUNT_NUM_LEN:HEADER_COUNT_NUM_LEN*2])[0] 471 | DHRp = header[HEADER_COUNT_NUM_LEN*2:] 472 | if self.keys['CKr']: 473 | self._stage_skipped_mk(self.keys['HKr'], self.nr, PNp, self.keys['CKr']) 474 | HKp = self.keys['NHKr'] 475 | RKp = hash_(self.keys['RK'] + generate_dh(self.keys['DHRs_priv'], DHRp)) 476 | NHKp = kdf(RKp, SALTS['NHK'][not self.mode]) 477 | CKp = kdf(RKp, SALTS['CK'][not self.mode]) 478 | CKp, mk = self._stage_skipped_mk(HKp, 0, Np, CKp) 479 | try: 480 | body = decrypt_symmetric(mk, msg[HEADER_LEN:]) 481 | except CryptoError: 482 | pass 483 | if not body or body == '': 484 | print 'Undecipherable message' 485 | sys.exit(1) 486 | self.keys['RK'] = RKp 487 | self.keys['HKr'] = HKp 488 | self.keys['NHKr'] = NHKp 489 | self.keys['DHRr'] = DHRp 490 | self.keys['DHRs_priv'] = None 491 | self.keys['DHRs'] = None 492 | self.ratchet_flag = True 493 | self.nr = Np + 1 494 | self.keys['CKr'] = CKp 495 | return body 496 | 497 | def encrypt_file(self, filename): 498 | with open(filename, 'r') as f: 499 | plaintext = f.read() 500 | ciphertext = b2a(self.encrypt(plaintext)) + '\n' 501 | with open(filename+'.asc', 'w') as f: 502 | lines = [ciphertext[i:i+64] for i in xrange(0, len(ciphertext), 64)] 503 | for line in lines: 504 | f.write(line+'\n') 505 | 506 | def decrypt_file(self, filename): 507 | with open(filename, 'r') as f: 508 | ciphertext = a2b(f.read()) 509 | plaintext = self.decrypt(ciphertext) 510 | print plaintext 511 | 512 | def encrypt_pipe(self): 513 | plaintext = sys.stdin.read() 514 | ciphertext = b2a(self.encrypt(plaintext)) + '\n' 515 | sys.stdout.write(ciphertext) 516 | sys.stdout.flush() 517 | 518 | def decrypt_pipe(self): 519 | ciphertext = a2b(sys.stdin.read()) 520 | plaintext = self.decrypt(ciphertext) 521 | sys.stdout.write(plaintext) 522 | sys.stdout.flush() 523 | 524 | def save(self): 525 | self._axolotl.save_conversation(self) 526 | 527 | def delete(self): 528 | self._axolotl.delete_conversation(self) 529 | 530 | def print_keys(self): 531 | print 'Your Identity key is:\n' + b2a(self.keys['DHIs']) + '\n' 532 | fingerprint = hash_(self.keys['DHIs']).encode('hex').upper() 533 | fprint = '' 534 | for i in range(0, len(fingerprint), 4): 535 | fprint += fingerprint[i:i+2] + ':' 536 | print 'Your identity key fingerprint is: ' 537 | print fprint[:-1] + '\n' 538 | print 'Your Ratchet key is:\n' + b2a(self.keys['DHRs']) + '\n' 539 | if self.handshake_key: 540 | print 'Your Handshake key is:\n' + b2a(self.handshake_pkey) 541 | else: 542 | print 'Your Handshake key is not available' 543 | 544 | def print_state(self): 545 | print 546 | print 'Warning: saving this data to disk is insecure!' 547 | print 548 | for key in sorted(self.keys): 549 | if 'priv' in key: 550 | pass 551 | else: 552 | if self.keys[key] is None: 553 | print key + ': None' 554 | elif type(self.keys[key]) is bool: 555 | if self.keys[key]: 556 | print key + ': True' 557 | else: 558 | print key + ': False' 559 | elif type(self.keys[key]) is str: 560 | try: 561 | self.keys[key].decode('ascii') 562 | print key + ': ' + self.keys[key] 563 | except UnicodeDecodeError: 564 | print key + ': ' + b2a(self.keys[key]) 565 | else: 566 | print key + ': ' + str(self.keys[key]) 567 | if self.mode is ALICE_MODE: 568 | print 'Mode: Alice' 569 | else: 570 | print 'Mode: Bob' 571 | 572 | 573 | class SkippedMessageKey: 574 | def __init__(self, mk, hk, timestamp): 575 | self.mk = mk 576 | self.hk = hk 577 | self.timestamp = timestamp 578 | 579 | 580 | class SqlitePersistence(object): 581 | def __init__(self, dbname, dbpassphrase, store_time, nonthreaded): 582 | super(SqlitePersistence, self).__init__() 583 | self.lock = Lock() 584 | self.dbname = dbname 585 | self.dbpassphrase = dbpassphrase 586 | self.store_time = store_time 587 | self.nonthreaded = nonthreaded 588 | 589 | self.db = self._open_db() 590 | 591 | def _open_db(self): 592 | db = sqlite3.connect(':memory:', check_same_thread=self.nonthreaded) 593 | db.row_factory = sqlite3.Row 594 | 595 | with db: 596 | try: 597 | if self.dbpassphrase is not None: 598 | with open(self.dbname, 'rb') as f: 599 | crypt_sql = f.read() 600 | try: 601 | sql = decrypt_symmetric(self.dbpassphrase, 602 | crypt_sql) 603 | except CryptoError: 604 | print 'Bad passphrase!' 605 | sys.exit(1) 606 | else: 607 | db.cursor().executescript(sql) 608 | else: 609 | with open(self.dbname, 'r') as f: 610 | sql = f.read() 611 | try: 612 | db.cursor().executescript(sql) 613 | except sqlite3.OperationalError: 614 | print 'Bad sql! Password problem - cannot create the database.' 615 | sys.exit(1) 616 | except IOError as e: 617 | if e.errno == errno.ENOENT: 618 | self._create_db(db) 619 | else: 620 | raise 621 | else: 622 | self._delete_expired_skipped_mk(db) 623 | return db 624 | 625 | def _create_db(self, db): 626 | db.execute(''' 627 | CREATE TABLE IF NOT EXISTS 628 | skipped_mk ( 629 | my_identity, 630 | to_identity, 631 | HKr TEXT, 632 | mk TEXT, 633 | timestamp INTEGER)''') 634 | db.execute(''' 635 | CREATE UNIQUE INDEX IF NOT EXISTS 636 | message_keys 637 | ON 638 | skipped_mk (mk)''') 639 | db.execute(''' 640 | CREATE TABLE IF NOT EXISTS 641 | conversations ( 642 | my_identity TEXT, 643 | other_identity TEXT, 644 | RK TEXT, 645 | HKs TEXT, 646 | HKr TEXT, 647 | NHKs TEXT, 648 | NHKr TEXT, 649 | CKs TEXT, 650 | CKr TEXT, 651 | DHIs_priv TEXT, 652 | DHIs TEXT, 653 | DHIr TEXT, 654 | DHRs_priv TEXT, 655 | DHRs TEXT, 656 | DHRr TEXT, 657 | CONVid TEXT, 658 | Ns INTEGER, 659 | Nr INTEGER, 660 | PNs INTEGER, 661 | ratchet_flag INTEGER, 662 | mode INTEGER)''') 663 | db.execute(''' 664 | CREATE UNIQUE INDEX IF NOT EXISTS 665 | conversation_route 666 | ON 667 | conversations ( 668 | my_identity, 669 | other_identity)''') 670 | 671 | def _delete_expired_skipped_mk(self, db): 672 | timestamp = int(time()) 673 | rowtime = timestamp - self.store_time 674 | db.execute(''' 675 | DELETE FROM 676 | skipped_mk 677 | WHERE 678 | timestamp < ?''', (rowtime,)) 679 | 680 | def _commit_skipped_mk(self, conversation): 681 | with self.db as db: 682 | db.execute(''' 683 | DELETE FROM 684 | skipped_mk 685 | WHERE 686 | my_identity = ? AND 687 | to_identity = ?''', ( 688 | conversation.name, 689 | conversation.other_name)) 690 | for skipped_mk in conversation.staged_hk_mk.values(): 691 | db.execute(''' 692 | INSERT INTO 693 | skipped_mk ( 694 | my_identity, 695 | to_identity, 696 | HKr, 697 | mk, 698 | timestamp) 699 | VALUES (?, ?, ?, ?, ?)''', ( 700 | conversation.name, 701 | conversation.other_name, 702 | b2a(skipped_mk.hk), 703 | b2a(skipped_mk.mk), 704 | skipped_mk.timestamp)) 705 | 706 | def _load_skipped_mk(self, name, other_name): 707 | skipped_hk_mk = dict() 708 | with self.db as db: 709 | rows = db.execute(''' 710 | SELECT 711 | * 712 | FROM 713 | skipped_mk 714 | WHERE 715 | my_identity = ? AND 716 | to_identity = ?''', (name, other_name)) 717 | for row in rows: 718 | mk = a2b(row['mk']) 719 | skipped_hk_mk[mk] = SkippedMessageKey(mk, 720 | hk=a2b(row['hkr']), 721 | timestamp=row['timestamp']) 722 | return skipped_hk_mk 723 | 724 | def write_db(self): 725 | with self.db as db: 726 | sql = bytes('\n'.join(db.iterdump())) 727 | if self.dbpassphrase is not None: 728 | crypt_sql = encrypt_symmetric(self.dbpassphrase, sql) 729 | with open(self.dbname, 'wb') as f: 730 | f.write(crypt_sql) 731 | else: 732 | with open(self.dbname, 'w') as f: 733 | f.write(sql) 734 | 735 | @sync 736 | def save_conversation(self, conversation): 737 | HKs = 0 if conversation.keys['HKs'] is None else b2a(conversation.keys['HKs']) 738 | HKr = 0 if conversation.keys['HKr'] is None else b2a(conversation.keys['HKr']) 739 | CKs = 0 if conversation.keys['CKs'] is None else b2a(conversation.keys['CKs']) 740 | CKr = 0 if conversation.keys['CKr'] is None else b2a(conversation.keys['CKr']) 741 | DHIr = 0 if conversation.keys['DHIr'] is None else b2a(conversation.keys['DHIr']) 742 | DHRs_priv = 0 if conversation.keys['DHRs_priv'] is None else b2a(conversation.keys['DHRs_priv']) 743 | DHRs = 0 if conversation.keys['DHRs'] is None else b2a(conversation.keys['DHRs']) 744 | DHRr = 0 if conversation.keys['DHRr'] is None else b2a(conversation.keys['DHRr']) 745 | ratchet_flag = 1 if conversation.ratchet_flag else 0 746 | mode = 1 if conversation.mode else 0 747 | with self.db as db: 748 | db.execute(''' 749 | REPLACE INTO 750 | conversations ( 751 | my_identity, 752 | other_identity, 753 | RK, 754 | HKS, 755 | HKr, 756 | NHKs, 757 | NHKr, 758 | CKs, 759 | CKr, 760 | DHIs_priv, 761 | DHIs, 762 | DHIr, 763 | DHRs_priv, 764 | DHRs, 765 | DHRr, 766 | CONVid, 767 | Ns, 768 | Nr, 769 | PNs, 770 | ratchet_flag, 771 | mode) 772 | VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 773 | ?, ?, ?)''', ( 774 | conversation.name, 775 | conversation.other_name, 776 | b2a(conversation.keys['RK']), 777 | HKs, 778 | HKr, 779 | b2a(conversation.keys['NHKs']), 780 | b2a(conversation.keys['NHKr']), 781 | CKs, 782 | CKr, 783 | b2a(conversation.keys['DHIs_priv']), 784 | b2a(conversation.keys['DHIs']), 785 | DHIr, 786 | DHRs_priv, 787 | DHRs, 788 | DHRr, 789 | b2a(conversation.keys['CONVid']), 790 | conversation.ns, 791 | conversation.nr, 792 | conversation.pns, 793 | ratchet_flag, 794 | mode)) 795 | self._commit_skipped_mk(conversation) 796 | self.write_db() 797 | 798 | @sync 799 | def load_conversation(self, axolotl, name, other_name): 800 | with self.db as db: 801 | cur = db.cursor() 802 | cur.execute(''' 803 | SELECT 804 | * 805 | FROM 806 | conversations 807 | WHERE 808 | my_identity = ? AND 809 | other_identity = ?''', (name, other_name)) 810 | row = cur.fetchone() 811 | if row: 812 | keys = \ 813 | { 'name': row['my_identity'], 814 | 'other_name': row['other_identity'], 815 | 'RK': a2b(row['rk']), 816 | 'NHKs': a2b(row['nhks']), 817 | 'NHKr': a2b(row['nhkr']), 818 | 'DHIs_priv': a2b(row['dhis_priv']), 819 | 'DHIs': a2b(row['dhis']), 820 | 'CONVid': a2b(row['convid']), 821 | 'Ns': row['ns'], 822 | 'Nr': row['nr'], 823 | 'PNs': row['pns'], 824 | } 825 | keys['HKs'] = None if row['hks'] == '0' else a2b(row['hks']) 826 | keys['HKr'] = None if row['hkr'] == '0' else a2b(row['hkr']) 827 | keys['CKs'] = None if row['cks'] == '0' else a2b(row['cks']) 828 | keys['CKr'] = None if row['ckr'] == '0' else a2b(row['ckr']) 829 | keys['DHIr'] = None if row['dhir'] == '0' else a2b(row['dhir']) 830 | keys['DHRs_priv'] = None if row['dhrs_priv'] == '0' else a2b(row['dhrs_priv']) 831 | keys['DHRs'] = None if row['dhrs'] == '0' else a2b(row['dhrs']) 832 | keys['DHRr'] = None if row['dhrr'] == '0' else a2b(row['dhrr']) 833 | ratchet_flag = row['ratchet_flag'] 834 | keys['ratchet_flag'] = True if ratchet_flag == 1 \ 835 | else False 836 | mode = row['mode'] 837 | mode = True if mode == 1 else False 838 | 839 | skipped_hk_mk = self._load_skipped_mk(name, other_name) 840 | 841 | # exit at first match 842 | return AxolotlConversation(axolotl, keys, mode, skipped_hk_mk) 843 | else: 844 | # if no matches 845 | return None 846 | 847 | @sync 848 | def delete_conversation(self, conversation): 849 | with self.db as db: 850 | db.execute(''' 851 | DELETE FROM 852 | skipped_mk 853 | WHERE 854 | to_identity = ?''', (conversation.other_name,)) 855 | db.execute(''' 856 | DELETE FROM 857 | conversations 858 | WHERE 859 | other_identity = ?''', (conversation.other_name,)) 860 | self.write_db() 861 | 862 | @sync 863 | def get_other_names(self, name): 864 | with self.db as db: 865 | rows = db.execute(''' 866 | SELECT 867 | other_identity 868 | FROM 869 | conversations 870 | WHERE 871 | my_identity = ?''', (name,)) 872 | return [row['other_identity'] for row in rows] 873 | 874 | 875 | def a2b(a): 876 | return Base64Encoder.decode(a) 877 | 878 | 879 | def b2a(b): 880 | return Base64Encoder.encode(b) 881 | 882 | 883 | def hash_(data): 884 | return sha256(data).decode('hex') 885 | 886 | 887 | def kdf(secret, salt): 888 | return pbkdf2(secret, salt, rounds=10, prf='hmac-sha256') 889 | 890 | 891 | Keypair = namedtuple('Keypair', 'priv pub') 892 | 893 | 894 | def generate_keypair(): 895 | privkey = PrivateKey.generate() 896 | return Keypair(bytes(privkey), bytes(privkey.public_key)) 897 | 898 | 899 | def generate_dh(a, b): 900 | a = PrivateKey(a) 901 | b = PublicKey(b) 902 | return bytes(Box(a, b)) 903 | 904 | 905 | def generate_3dh(a, a0, b, b0, mode=ALICE_MODE): 906 | if mode is ALICE_MODE: 907 | return hash_(generate_dh(a, b0) + 908 | generate_dh(a0, b) + 909 | generate_dh(a0, b0)) 910 | else: 911 | return hash_(generate_dh(a0, b) + 912 | generate_dh(a, b0) + 913 | generate_dh(a0, b0)) 914 | 915 | 916 | def encrypt_symmetric(key, plaintext): 917 | nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE) 918 | box = nacl.secret.SecretBox(key) 919 | return bytes(box.encrypt(plaintext, nonce)) 920 | 921 | 922 | def decrypt_symmetric(key, ciphertext): 923 | box = nacl.secret.SecretBox(key) 924 | return box.decrypt(ciphertext) 925 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------