Exemplo n.º 1
0
def decrypt(data: str, gpg: GPG) -> str:
    """
    Decrypt `data` with `gpg` and return its value.
    """
    result = gpg.decrypt(data, always_trust=True)

    if not result.ok:
        raise DecryptionError(result.status)
    else:
        return str(gpg.decrypt(data, always_trust=True))
Exemplo n.º 2
0
class DecryptMessage(Resource):
    def __init__(self):
        self.gpg = GPG(gpgbinary='/usr/bin/gpg',
                       gnupghome='/usr/local/src/keys')

    def post(self):
        parser = reqparse.RequestParser(bundle_errors=True)
        parser.add_argument('Message',
                            type=str,
                            required=True,
                            location='json')
        parser.add_argument('Passphrase',
                            type=str,
                            required=True,
                            location='json')
        args = parser.parse_args(strict=True)

        if not args['Message'] or not args['Passphrase']:
            return {"Error": "Invalid Message or Passphrase"}

        decrypted = self.gpg.decrypt(args['Message'],
                                     passphrase=args['Passphrase'])

        if decrypted.ok:
            return {"DecryptedMessage": str(decrypted)}
        else:
            return {"Error": decrypted.status}
Exemplo n.º 3
0
def finish_auth_pass(message, bot):
    t_str = 'test_ur_crappy_password_str'
    decrypt = None

    try:
        gpg = GPG()
        encrypt = gpg.encrypt(t_str, recipients='user_' + str(message.chat.id))
        decrypt = gpg.decrypt(str(encrypt), passphrase=str(message.text))
        system('echo RELOADAGENT | gpg-connect-agent')

    except:
        msg = bot.send_message(message.chat.id, 'Произошла ошибка.')
        del_mess(msg, bot, 4)
        result_available.set()

    if str(decrypt) == t_str:
        global pas
        msg = bot.send_message(message.chat.id, 'Вы аутентифицировались.')
        pas = str(message.text)
        del_mess(msg, bot, 4)
        result_available.set()

    else:
        msg = bot.send_message(message.chat.id, 'Пароль не верен.')
        del_mess(msg, bot, 4)
        result_available.set()
Exemplo n.º 4
0
def get_gpg_pwd(apistatus, userid_status, mfa, userid, g_home, g_pass):
    """Returns gpg password if all inputs are valid.

    Keyword arguments:
    apistatus - The true/false return value from the check_api_key
    function.
    userid_stauts - The true/false return value from the check_userid
    function.
    mfa - The true/false return value from the check_totp
    function.
    userid -  The userid that corresponds (key:value) to sensitive data
    that is being retrieved.
    g_home - The GPG home directory for this application, i.e.
    export |grep GNUPGHOME.
    g_pass - The password for the GPG private key.

    Output:
    The function returns the sensitive data that corresponds to the
    userid."""
    # Performing input validation.
    if not validate_userid(userid):
        return 1
    # Checking login status and that the API key is authorized to
    # access the userid.
    if apistatus and userid_status and mfa:
        gpg_file = open(c_text, 'r', encoding='ascii').read().strip('\n')
        g = GPG(homedir=g_home)
        gpg_data = str(g.decrypt(gpg_file, passphrase=g_pass)).split('\n')
        for line in gpg_data:
            reg_search = search(r'(^' + userid + ': )(.+)', line)
            if reg_search:
                return reg_search.group(2)
    else:
        return False
Exemplo n.º 5
0
    def do_job_unit(self, event, corpus, unit, **kwargs):
        preroll = kwargs.get("preroll", 0)
        
        for i, (domain, count, path, url) in enumerate(self.get_chunk_info_paths_urls(
                event, corpus, preroll=preroll)):
            if i != unit:
                continue
            gpg = GPG()
            
            #http = urllib3.PoolManager()
            parent = os.path.dirname(path)
            if not os.path.exists(parent):
                try:
                    os.makedirs(parent)
                except OSError as e:
                    if e.errno == errno.EEXIST and os.path.isdir(parent):
                        pass

            retries = 3
            while 1:
                try:
                    r = requests.get(url, timeout=30)
                    with open(path, u'wb') as f:
                        f.write(str(gpg.decrypt(r.content)))
                    break
                except requests.exceptions.ConnectionError:
                    retries -= 1
                    if retries == 0:
                        break

                except urllib3.exceptions.ReadTimeoutError:
                    retries -= 1
                    if retries == 0:
                        break
Exemplo n.º 6
0
    def do_job_unit(self, event, corpus, unit, **kwargs):
        preroll = kwargs.get("preroll", 0)

        for i, (domain, count, path, url) in enumerate(
                self.get_chunk_info_paths_urls(event, corpus,
                                               preroll=preroll)):
            if i != unit:
                continue
            gpg = GPG()

            #http = urllib3.PoolManager()
            parent = os.path.dirname(path)
            if not os.path.exists(parent):
                try:
                    os.makedirs(parent)
                except OSError as e:
                    if e.errno == errno.EEXIST and os.path.isdir(parent):
                        pass

            retries = 3
            while 1:
                try:
                    r = requests.get(url, timeout=30)
                    with open(path, u'wb') as f:
                        f.write(str(gpg.decrypt(r.content)))
                    break
                except requests.exceptions.ConnectionError:
                    retries -= 1
                    if retries == 0:
                        break

                except urllib3.exceptions.ReadTimeoutError:
                    retries -= 1
                    if retries == 0:
                        break
Exemplo n.º 7
0
def finish_clone_pass(message, bot, path_to_user_folder):

	t_str = 'test_ur_crappy_password_str'
	decrypt = None

	try:
		gpg = GPG()
		encrypt = gpg.encrypt(t_str, recipients='user_'+str(message.chat.id))
		decrypt = gpg.decrypt(str(encrypt), passphrase=message.text)
		system('echo RELOADAGENT | gpg-connect-agent')

	except:
	 	msg = bot.send_message(message.chat.id, 'Произошла ошибка.')
	 	del_mess(msg, bot, 8)
	 	return

	if str(decrypt) == t_str:
		try:
			with open(path_to_user_folder+'/user_data/Nothing.txt', 'w') as f:
				f.write(message.text)
			msg = bot.send_message(message.chat.id, 'Пароль сохранен.', reply_markup = types.ReplyKeyboardRemove(selective=False))
			del_mess(msg, bot, 8)
			return

		except:
			msg = bot.send_message(message.chat.id, 'Произошла ошибка.', reply_markup = types.ReplyKeyboardRemove(selective=False))
			del_mess(msg, bot, 8)
			return

	else:
		msg = bot.send_message(message.chat.id, 'Пароль не верен.')
		msg_handler = bot.send_message(message.chat.id, 'Введите пароль от нового ключа, я его сохраню.', reply_markup = types.ReplyKeyboardRemove(selective=False))
		bot.register_next_step_handler(msg_handler, lambda msg: finish_clone_pass(msg, bot, path_to_user_folder))
Exemplo n.º 8
0
def extract_content(path, keyring, output_dir, output_ext):
    """ Use the keyring to decrypt a document """
    name = os.path.splitext(os.path.basename(path))[0]
    gpg = GPG(gnupghome=keyring)
    new_path = os.path.join(output_dir, '.'.join([name, output_ext]))
    try:
        with open(path, 'rb') as content:
            data = gpg.decrypt(content.read(), output=new_path)
    except OSError:
        raise DecryptionError("Could not open '%s'" % path, path)
    return new_path
Exemplo n.º 9
0
def extract_content(path, keyring, output_dir, output_ext):
    """ Use the keyring to decrypt a document """
    name = os.path.splitext(os.path.basename(path))[0]
    gpg = GPG(gnupghome=keyring)
    new_path = os.path.join(output_dir, '.'.join([name, output_ext]))
    try:
        with open(path, 'rb') as content:
            data = gpg.decrypt(content.read(), output=new_path)
    except OSError:
        raise DecryptionError("Could not open '%s'" % path, path)
    return new_path
Exemplo n.º 10
0
    def _pgp_decrypt(self, encrypted_firmware, key):
        '''
        This does the actual decryption.
        '''
        try:
            tmp_dir = tempfile.mkdtemp()
            gpg = GPG(gnupghome=tmp_dir)
            gpg.import_keys(key)
            decrypted_data = gpg.decrypt(encrypted_firmware)
        finally:
            try:
                shutil.rmtree(tmp_dir)
            except OSError as exc:
                if exc.errno != errno.ENOENT:
                    raise

        return bytes(decrypted_data.data)
Exemplo n.º 11
0
def decrypt(message):
    '''
    decrypt a message sent to me, and verify sender email
    '''
    gpg = GPG()
    verified = decoded = b''
    logging.debug('decoding %s...', message[:64])
    try:
        decoded = b58decode(message)
        logging.debug('decrypting %r...', decoded[:64])
        decrypted = gpg.decrypt(decoded)
        # pylint: disable=no-member
        verified = 'trust level %s' % decrypted.trust_text
    except ValueError:
        logging.warning('%r... not base58 encoded', message[:32])
        decrypted = type('', (), {'data': message})
        verified = 'unencoded'
    except subprocess.CalledProcessError as problem:
        logging.exception(problem)
        decrypted = type('', (), {'data': b''})
    return decrypted.data, verified
Exemplo n.º 12
0
Arquivo: sc.py Projeto: kedz/cuttsum
def scchunk_worker_(job_queue, result_queue, **kwargs):
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    gpg = GPG()
    http = urllib3.PoolManager(timeout=15.0, retries=3)

    while not job_queue.empty():
        try:
            path, url = job_queue.get(block=False)
            parent = os.path.dirname(path)
            if not os.path.exists(parent):
                try:
                    os.makedirs(parent)
                except OSError as e: 
                    if e.errno == errno.EEXIST and os.path.isdir(parent):
                        pass

            r = http.request('GET', url)
            with open(path, u'wb') as f:
                f.write(str(gpg.decrypt(r.data)))
            result_queue.put(None)
        except Queue.Empty:
            pass
Exemplo n.º 13
0
def scchunk_worker_(job_queue, result_queue, **kwargs):
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    gpg = GPG()
    http = urllib3.PoolManager(timeout=15.0, retries=3)

    while not job_queue.empty():
        try:
            path, url = job_queue.get(block=False)
            parent = os.path.dirname(path)
            if not os.path.exists(parent):
                try:
                    os.makedirs(parent)
                except OSError as e:
                    if e.errno == errno.EEXIST and os.path.isdir(parent):
                        pass

            r = http.request('GET', url)
            with open(path, u'wb') as f:
                f.write(str(gpg.decrypt(r.data)))
            result_queue.put(None)
        except Queue.Empty:
            pass
Exemplo n.º 14
0
#!/usr/bin/env python
import requests
from gnupg import GPG

passphrase = None

if __name__ == "__main__":
    gpg = GPG()
    url = "http://127.0.0.1:8000/students/crypto/"
    r = requests.get(url)
    print "cifrado", r.text
    content = gpg.decrypt(r.text, always_trust=True, passphrase=passphrase)
    print "decifrado"
    if not content:
        print "No se pudo descifrar"
    else:
        print content
Exemplo n.º 15
0
Arquivo: crypto.py Projeto: 10sr/junks
def dec(data, key):
    gpg = GPG()
    return gpg.decrypt()
Exemplo n.º 16
0
def decrypt(data: str, gpg: GPG) -> str:
    """
    Decrypt `data` with `gpg` and return its value.
    """
    return str(gpg.decrypt(data, always_trust=True))
Exemplo n.º 17
0
class GpgSandbox:
    """
    The GPG sandbox wraps a :class:`gnupg.GPG` instance that uses a temporary directory as its home directory. This
    allows to import keys without messing with the user's system. It automatically imports files named `*.key` placed
    in `keys_dir` (`data/keys`) by default. The keys can then be referenced by their filename minus the `.key`
    extension, for example `john.doe.key` can then be used with `gpg.get_key('john.doe').
    """
    def __init__(self, tmpdir: str, keys_dir: str = 'data/keys') -> None:
        # GPG needs the homedir to have limited permissions
        os.chmod(tmpdir, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)

        self.homedir = tmpdir
        self.gpg = GPG(gnupghome=tmpdir)
        self.keys = self.import_keys(keys_dir)

    def get_key_files(self, keys_dir: str) -> Iterable[str]:
        """
        Return the list of key files in the keys directory.
        """
        return glob.glob(
            os.path.join(os.path.dirname(__file__), '..', keys_dir, '*.key'))

    def import_key(self, key: str) -> str:
        """
        Import the given armored key and return its fingerprint.
        """
        import_result = self.gpg.import_keys(key)

        return import_result.fingerprints[0]

    def import_keys(self, keys_dir: str) -> Dict[str, Tuple[str, str]]:
        """
        Iterate over the `.key` files in `keys_dir` and import then into GPG.
        """
        keys = {}

        for key_path in self.get_key_files(keys_dir):
            username = os.path.basename(key_path)[:-len('.key')]

            with open(key_path) as key_file:
                key = key_file.read()

            keys[username] = (self.import_key(key), key)

        return keys

    def encrypt(self, data: str, username: str) -> str:
        """
        Return `data` encrypted for `username`, which should match a key in the keys directory.
        """
        return str(
            self.gpg.encrypt(data, self.keys[username][0], always_trust=True))

    def decrypt(self, data: str) -> str:
        """
        Return `data` decrypted. A corresponding private key must be available so this data can be decrypted.
        """
        return str(self.gpg.decrypt(data, always_trust=True))

    def get_fingerprint(self, username: str) -> str:
        """
        Return the key fingerprint of the given username.
        """
        return self.keys[username][0]

    def get_key(self, username: str) -> str:
        """
        Return the armored key of the given username.
        """
        return self.keys[username][1]
Exemplo n.º 18
0
gpg = GPG(binary='/usr/bin/gpg2',
          homedir='~/.gnupg',
          keyring='pubring.gpg',
          secring='secring.gpg')

stored_keys = gpg.list_keys()

message = "This is a test message to be encripted."

options_enc = {
    'passphrase': passphrase,
    'armor': True,
    'default_key': gpg_test_fingerprint
    }
encrypted_msg = gpg.encrypt(message, gpg_test_fingerprint, **options_enc)

print(encrypted_msg)

options_dec = {
    'passphrase': passphrase
    }
decrypted_msg = gpg.decrypt(str(encrypted_msg), **options_dec)

assert message == str(decrypted_msg)

print("This is the original message:", decrypted_msg)

''' "Valid" will return a boolean saying whether the decrypted message's
signature is valid.'''
assert decrypted_msg.valid
Exemplo n.º 19
0
def DecryptGPG(cipher_file, gpghome, p_phrase):
    """Simple decrypt."""
    cipher_data = str(open(cipher_file, 'r').read()).strip('\n')
    g = GPG(gnupghome=gpghome)
    clear_data = g.decrypt(cipher_data, passphrase=p_phrase)
    return clear_data
Exemplo n.º 20
0
class Axolotl:
    def __init__(self, name, dbname='axolotl.db', dbpassphrase='',
                 user_pathstring='~'):
        self.ratchetKey = None
        self.ratchetPKey = None
        self.name = name
        self.db = None
        self.mode = None
        self.staged_HK_mk = None
        self.state = None
        self.handshakeKey = None
        self.handshakePKey = None
        self.storeTime = None

        user_path = os.path.expanduser(user_pathstring)
        keyring = [user_path + '/.gnupg/pubring.gpg']
        secret_keyring = [user_path + '/.gnupg/secring.gpg']

        self.dbname = user_path + '/tmp/pyaxo_db/' + dbname

        self.gpg = GPG(gnupghome=user_path + '/.axolotl', gpgbinary='gpg',
                       keyring=keyring,
                       secret_keyring=secret_keyring,
                       options=['--throw-keyids',
                                '--personal-digest-preferences=sha256',
                                '--s2k-digest-algo=sha256'])
        self.gpg.encoding = 'utf-8'

        if dbpassphrase != '' or dbpassphrase is None:
            self.dbpassphrase = dbpassphrase
        else:
            self.dbpassphrase = getpass(
                'Database passphrase for ' + self.name + ': ').strip()

        self.db_init()

    def db_init(self):

        try:
            self.db = self.open_db()
        except sqlite3.OperationalError:
            raise (Axolotl_exception('Bad sql! Password problem - \
            cannot create the database.'))

        self.mode = None
        self.staged_HK_mk = {}

        self.state = {}
        self.state['DHIs_priv'], self.state['DHIs'] = self.genKey()
        self.state['DHRs_priv'], self.state['DHRs'] = self.genKey()

        self.handshakeKey, self.handshakePKey = self.genKey()

        # minimum time (seconds) to store missed ephemeral message keys
        self.storeTime = 2 * 86400
        with self.db:
            cur = self.db.cursor()

            cur.execute("""
            CREATE TABLE IF NOT EXISTS skipped_mk
            (my_identity, to_identity, HKr TEXT, mk TEXT,
              timestamp INTEGER )""")

            cur.execute("""
            CREATE UNIQUE INDEX IF NOT EXISTS
                         message_keys ON skipped_mk (mk)""")

            cur.execute("""
            CREATE TABLE IF NOT EXISTS conversations
            (my_identity TEXT, other_identity TEXT, RK TEXT, HKs TEXT,
              HKr TEXT, NHKs TEXT, NHKr TEXT, CKs TEXT, CKr TEXT,
              DHIs_priv TEXT, DHIs TEXT, DHIr TEXT, DHRs_priv TEXT,
              DHRs TEXT, DHRr TEXT, CONVid TEXT, Ns INTEGER, Nr INTEGER,
              PNs INTEGER, ratchet_flag INTEGER, mode INTEGER)""")

            cur.execute("""
            CREATE UNIQUE INDEX IF NOT EXISTS
                         conversation_route ON
                         conversations (my_identity, other_identity)""")
        self.commit_skipped_mk()

    def triple_dh(self, a, a0, B, B0):
        if self.mode is None:
            raise (Axolotl_exception('Mode must be set'))
        if self.mode:
            return sha256(
                self.gen_dh(a, B0) + self.gen_dh(a0, B) +
                self.gen_dh(a0, B0)).digest()
        else:
            return sha256(
                self.gen_dh(a0, B) + self.gen_dh(a, B0) +
                self.gen_dh(a0, B0)).digest()

    def initState(self, other_name, other_identityKey, other_handshakeKey,
                  other_ratchetKey, verify=True):
        if verify:
            print('Confirm ' + other_name + ' has identity key fingerprint:\n')
            fingerprint = sha224(other_identityKey).hexdigest().upper()
            fprint = ''
            for i in range(0, len(fingerprint), 4):
                fprint += fingerprint[i:i + 2] + ':'
            print(fprint[:-1] + '\n')
            print('Be sure to verify this fingerprint with ' + other_name +
                  ' by some out-of-band method!')
            print('Otherwise, you may be subject to a \
            Man-in-the-middle attack!\n')
            ans = raw_input('Confirm? y/N: ').strip()
            if ans != 'y':
                raise (Axolotl_exception('Key fingerprint \
                not confirmed - exception'))

        if self.state['DHIs'] < other_identityKey:
            self.mode = True
        else:
            self.mode = False
        mkey = self.triple_dh(self.state['DHIs_priv'], self.handshakeKey,
                              other_identityKey, other_handshakeKey)

        self.createState(other_name, mkey,
                         mode=self.mode,
                         other_identityKey=other_identityKey,
                         other_ratchetKey=other_ratchetKey)

    def createState(self, other_name, mkey, mode=None, other_identityKey=None,
                    other_ratchetKey=None):
        self.mode = mode

        if self.mode is None:  # mode not selected
            raise (Axolotl_exception('Mode must be set'))
        if self.mode:  # alice mode
            RK = pbkdf2(mkey, b'\x00', 10, prf='hmac-sha256')
            HKs = None
            HKr = pbkdf2(mkey, b'\x02', 10, prf='hmac-sha256')
            NHKs = pbkdf2(mkey, b'\x03', 10, prf='hmac-sha256')
            NHKr = pbkdf2(mkey, b'\x04', 10, prf='hmac-sha256')
            CKs = None
            CKr = pbkdf2(mkey, b'\x06', 10, prf='hmac-sha256')
            DHRs_priv = None
            DHRs = None
            DHRr = other_ratchetKey
            CONVid = pbkdf2(mkey, b'\x07', 10, prf='hmac-sha256')
            Ns = 0
            Nr = 0
            PNs = 0
            ratchet_flag = True
        else:  # bob mode
            RK = pbkdf2(mkey, b'\x00', 10, prf='hmac-sha256')
            HKs = pbkdf2(mkey, b'\x02', 10, prf='hmac-sha256')
            HKr = None
            NHKs = pbkdf2(mkey, b'\x04', 10, prf='hmac-sha256')
            NHKr = pbkdf2(mkey, b'\x03', 10, prf='hmac-sha256')
            CKs = pbkdf2(mkey, b'\x06', 10, prf='hmac-sha256')
            CKr = None
            DHRs_priv = self.state['DHRs_priv']
            DHRs = self.state['DHRs']
            DHRr = None
            CONVid = pbkdf2(mkey, b'\x07', 10, prf='hmac-sha256')
            Ns = 0
            Nr = 0
            PNs = 0
            ratchet_flag = False
        DHIr = other_identityKey

        self.state = \
            {'name': self.name, 'other_name': other_name, 'RK': RK,
             'HKs': HKs, 'HKr': HKr, 'NHKs': NHKs, 'NHKr': NHKr, 'CKs': CKs,
             'CKr': CKr, 'DHIs_priv': self.state['DHIs_priv'],
             'DHIs': self.state['DHIs'], 'DHIr': DHIr,
             'DHRs_priv': DHRs_priv, 'DHRs': DHRs, 'DHRr': DHRr,
             'CONVid': CONVid, 'Ns': Ns, 'Nr': Nr, 'PNs': PNs,
             'ratchet_flag': ratchet_flag,
             }

        self.ratchetKey = False
        self.ratchetPKey = False

    def encrypt(self, plaintext):
        if self.state['ratchet_flag']:
            self.state['DHRs_priv'], self.state['DHRs'] = self.genKey()
            self.state['HKs'] = self.state['NHKs']
            self.state['RK'] = sha256(self.state['RK'] +
                                      self.gen_dh(
                                          self.state['DHRs_priv'],
                                          self.state['DHRr'])).digest()
            if self.mode:
                self.state['NHKs'] = pbkdf2(self.state['RK'], b'\x03', 10,
                                            prf='hmac-sha256')
                self.state['CKs'] = pbkdf2(self.state['RK'], b'\x05', 10,
                                           prf='hmac-sha256')
            else:
                self.state['NHKs'] = pbkdf2(self.state['RK'], b'\x04', 10,
                                            prf='hmac-sha256')
                self.state['CKs'] = pbkdf2(self.state['RK'], b'\x06', 10,
                                           prf='hmac-sha256')
            self.state['PNs'] = self.state['Ns']
            self.state['Ns'] = 0
            self.state['ratchet_flag'] = False
        mk = sha256(self.state['CKs'] + '0').digest()
        msg1 = self.enc(self.state['HKs'], str(self.state['Ns']).zfill(3) +
                        str(self.state['PNs']).zfill(3) + self.state['DHRs'])
        msg2 = self.enc(mk, plaintext)
        pad_length = 106 - len(msg1)
        pad = os.urandom(pad_length - 1) + chr(pad_length)
        msg = msg1 + pad + msg2
        self.state['Ns'] += 1
        self.state['CKs'] = sha256(self.state['CKs'] + '1').digest()
        return msg

    def commit_skipped_mk(self):
        timestamp = int(time())
        with self.db:
            cur = self.db.cursor()
            for mk, HKr in self.staged_HK_mk.iteritems():
                cur.execute("""REPLACE INTO skipped_mk (my_identity,
                  to_identity, HKr, mk, timestamp ) VALUES (?, ?, ?, ?, ?)""",
                            self.state['name'],
                            self.state['other_name'],
                            b2a_base64(HKr).strip(),
                            b2a_base64(mk).strip(),
                            timestamp)

            rowtime = timestamp - self.storeTime
            cur.execute('DELETE FROM skipped_mk WHERE timestamp < ?',
                        (rowtime,))

    def trySkippedMK(self, msg, pad_length, name, other_name):
        with self.db:
            cur = self.db.cursor()
            cur.execute('SELECT * FROM skipped_mk')
            rows = cur.fetchall()
            for row in rows:
                if name == row[0] and other_name == row[1]:
                    msg1 = msg[:106 - pad_length]
                    msg2 = msg[106:]
                    header = self.dec(a2b_base64(row[2]), msg1)
                    body = self.dec(a2b_base64(row[3]), msg2)
                    if header != '' and body != '':
                        cur.execute('DELETE FROM skipped_mk WHERE mk = ?',
                                    (row[3],))
                        return body
        return False

    def stageSkippedMK(self, HKr, Nr, Np, CKr):
        CKp = CKr
        for i in range(Np - Nr):
            mk = sha256(CKp + '0').digest()
            CKp = sha256(CKp + '1').digest()
            self.staged_HK_mk[mk] = HKr

        mk = sha256(CKp + '0').digest()
        CKp = sha256(CKp + '1').digest()
        return CKp, mk

    def decrypt(self, msg):
        pad = msg[105:106]
        pad_length = ord(pad)
        msg1 = msg[:106 - pad_length]

        body = self.trySkippedMK(msg, pad_length, self.state['name'],
                                 self.state['other_name'])
        if body and body != '':
            return body

        header = None
        if self.state['HKr']:
            header = self.dec(self.state['HKr'], msg1)
        if header and header != '':
            Np = int(header[:3])
            CKp, mk = self.stageSkippedMK(self.state['HKr'], self.state['Nr'],
                                          Np, self.state['CKr'])
            body = self.dec(mk, msg[106:])
            if not body or body == '':
                raise (Axolotl_exception('Undecipherable message'))
        else:
            header = self.dec(self.state['NHKr'], msg1)
            if self.state['ratchet_flag'] or not header or header == '':
                raise (Axolotl_exception('Undecipherable message'))

            Np = int(header[:3])
            PNp = int(header[3:6])
            DHRp = header[6:]
            if self.state['CKr']:
                self.stageSkippedMK(self.state['HKr'], self.state['Nr'], PNp,
                                    self.state['CKr'])
            HKp = self.state['NHKr']
            RKp = sha256(
                self.state['RK'] + self.gen_dh(self.state['DHRs_priv'],
                                               DHRp)).digest()
            if self.mode:
                NHKp = pbkdf2(RKp, b'\x04', 10, prf='hmac-sha256')
                CKp = pbkdf2(RKp, b'\x06', 10, prf='hmac-sha256')
            else:
                NHKp = pbkdf2(RKp, b'\x03', 10, prf='hmac-sha256')
                CKp = pbkdf2(RKp, b'\x05', 10, prf='hmac-sha256')
            CKp, mk = self.stageSkippedMK(HKp, 0, Np, CKp)
            body = self.dec(mk, msg[106:])
            if not body or body == '':
                raise (Axolotl_exception('Undecipherable message'))

            self.state['RK'] = RKp
            self.state['HKr'] = HKp
            self.state['NHKr'] = NHKp
            self.state['DHRr'] = DHRp
            self.state['DHRs_priv'] = None
            self.state['DHRs'] = None
            self.state['ratchet_flag'] = True
        self.commit_skipped_mk()
        self.state['Nr'] = Np + 1
        self.state['CKr'] = CKp
        return body

    def encrypt_file(self, filename):
        with open(filename, 'r') as f:
            plaintext = f.read()
        ciphertext = b2a_base64(self.encrypt(plaintext))
        with open(filename + '.asc', 'w') as f:
            lines = [ciphertext[i:i + 64] for i in
                     xrange(0, len(ciphertext), 64)]
            for line in lines:
                f.write(line + '\n')

    def decrypt_file(self, filename):
        with open(filename, 'r') as f:
            ciphertext = a2b_base64(f.read())
        plaintext = self.decrypt(ciphertext)
        print(plaintext)

    def encrypt_pipe(self):
        plaintext = sys.stdin.read()
        ciphertext = b2a_base64(self.encrypt(plaintext))
        sys.stdout.write(ciphertext)
        sys.stdout.flush()

    def decrypt_pipe(self):
        ciphertext = a2b_base64(sys.stdin.read())
        plaintext = self.decrypt(ciphertext)
        sys.stdout.write(plaintext)
        sys.stdout.flush()

    def printKeys(self):
        print('Your Identity key is:\n' + b2a_base64(
            self.state['DHIs']))
        fingerprint = sha224(self.state['DHIs']).hexdigest().upper()
        fprint = ''
        for i in range(0, len(fingerprint), 4):
            fprint += fingerprint[i:i + 2] + ':'
        print('Your identity key fingerprint is: ')
        print(fprint[:-1] + '\n')
        print('Your Ratchet key is:\n' + b2a_base64(
            self.state['DHRs']))
        if self.handshakeKey:
            print('Your Handshake key is:\n' + b2a_base64(
                self.handshakePKey))
        else:
            print('Your Handshake key is not available')

    def to_json(self):
        _j = {'name': self.name,
              'identity_key': b2a_base64(self.state('DHIs')),
              'fingerprint': sha224(self.state['DHIs']).hexdigest().upper(),
              'ratchet_key': b2a_base64(self.state['DHRs'])}
        return json.dumps(_j)

    def init_from_json(self, _jsn):
        _k = json.loads(_jsn)
        self.initState(_k['name'], a2b_base64(_k['identity_key']),
                       a2b_base64(_k['fingerprint']),
                       a2b_base64(_k['ratchet_key']))
        self.saveState()

    def saveState(self):
        ktup = ('HKs', 'HKr', 'CKs', 'CKR', 'DHIr', 'DHRs_priv', 'DHRs')

        v = {k: b2a_base64(self.state[k]).strip for k in ktup}

        ratchet_flag = 1 if self.state['ratchet_flag'] else 0
        mode = 1 if self.mode else 0
        with self.db:
            cur = self.db.cursor()
            cur.execute("""\
            REPLACE INTO conversations (
                       my_identity, other_identity, RK,HKS, HKr, NHKs, NHKr,
                       CKs, CKr, DHIs_priv, DHIs, DHIr, DHRs_priv, DHRs,
                       DHRr, CONVid, Ns, Nr, PNs, ratchet_flag, mode)
                       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
                       ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
                        (self.state['name'],
                         self.state['other_name'],
                         b2a_base64(self.state['RK']).strip(),
                         v['HKs'], v['HKr'],
                         b2a_base64(self.state['NHKs']).strip(),
                         b2a_base64(self.state['NHKr']).strip(),
                         v['CKs'], v['CKr'],
                         b2a_base64(self.state['DHIs_priv']).strip(),
                         b2a_base64(self.state['DHIs']).strip(),
                         v['DHIr'], v['DHRs_priv'], v['DHRs'], v['DHRr'],
                         b2a_base64(self.state['CONVid']).strip(),
                         self.state['Ns'], self.state['Nr'], self.state['PNs'],
                         ratchet_flag,
                         mode
                         ))
        self.write_db()

    def loadState(self, name, other_name):
        self.db = self.open_db()
        with self.db:
            cur = self.db.cursor()
            try:
                cur.execute('SELECT * FROM conversations')
            except sqlite3.OperationalError:
                raise (Axolotl_exception('Bad sql! Password problem - \
                cannot loadState()'))

            rows = cur.fetchall()
            for row in rows:
                if row[0] == name and row[1] == other_name:
                    self.state = {'name': row[0],
                                  'other_name': row[1],
                                  'RK': a2b_base64(row[2]),
                                  'NHKs': a2b_base64(row[5]),
                                  'NHKr': a2b_base64(row[6]),
                                  'DHIs_priv': a2b_base64(row[9]),
                                  'DHIs': a2b_base64(row[10]),
                                  'CONVid': a2b_base64(row[15]),
                                  'Ns': row[16],
                                  'Nr': row[17],
                                  'PNs': row[18]}

                    self.name = self.state['name']

                    def do_bin(loc):
                        if row[loc] == '0':
                            return None
                        else:
                            return a2b_base64(row[loc])

                    self.state['HKs'] = do_bin(3)
                    self.state['HKr'] = do_bin(4)
                    self.state['CKs'] = do_bin(7)
                    self.state['CKr'] = do_bin(8)
                    self.state['DHIr'] = do_bin(11)
                    self.state['DHRs_priv'] = do_bin(12)
                    self.state['DHRs'] = do_bin(13)
                    self.state['DHRr'] = do_bin(14)

                    ratchet_flag = row[19]
                    if ratchet_flag == 1:
                        self.state['ratchet_flag'] = True
                    else:
                        self.state['ratchet_flag'] = False

                    mode = row[20]
                    self.mode = True if mode == 1 else False
                    return  # exit at first match
            return False  # if no matches

    def open_db(self):

        db = sqlite3.connect(':memory:')

        try:
            with open(self.dbname, 'rb') as f:
                if self.dbpassphrase is not None:
                    sql = \
                        self.gpg.decrypt_file(f, passphrase=self.dbpassphrase)

                    if sql is not None and sql != '':
                        db.cursor().executescript(sql.data)
                        return db
                    else:
                        raise (Axolotl_exception('Bad passphrase!'))
                else:
                    sql = f.read()
                    db.cursor().executescript(sql)
                    return db
        except IOError:
            return db

    def write_db(self):

        sql = ''
        for item in self.db.iterdump():
            sql = sql + item + '\n'
        if self.dbpassphrase is not None:
            crypt_sql = self.gpg.encrypt(sql, recipients=None,
                                         symmetric='AES256',
                                         armor=False,
                                         always_trust=True,
                                         passphrase=self.dbpassphrase)

            with open(self.dbname, 'wb') as f:
                f.write(crypt_sql.data)
        else:
            with open(self.dbname, 'w') as f:
                f.write(sql)

    def print_state(self):

        print('\nWarning: saving this data to disk is insecure!\n')

        for key in sorted(self.state):
            if 'priv' in key:
                pass
            else:
                if self.state[key] is None:
                    print(key + ': None')
                elif type(self.state[key]) is bool:
                    if self.state[key]:
                        print(key + ': True')
                    else:
                        print(key + ': False')
                elif type(self.state[key]) is str:
                    try:
                        self.state[key].decode('ascii')
                        print(key + ': ' + self.state[key])
                    except UnicodeDecodeError:
                        print(key + ': ' + b2a_base64(
                            self.state[key]).strip())
                else:
                    print(key + ': ' + str(self.state[key]))
        if self.mode:
            print('Mode: Alice')
        else:
            print('Mode: Bob')

    @staticmethod
    def genKey():
        key = keys.Private()
        privkey = key.private
        pubkey = key.get_public().serialize()
        return privkey, pubkey

    @staticmethod
    def gen_dh(a, B):
        key = keys.Private(secret=a)
        return key.get_shared_key(keys.Public(B))

    def dec(self, key, encrypted):
        key = hexlify(key)
        msg = self.gpg.decrypt(GPG_HEADER + encrypted,
                               passphrase=key, always_trust=True)
        return msg.data

    def enc(self, key, plaintext):
        key = hexlify(key)
        msg = self.gpg.encrypt(plaintext, recipients=None,
                               symmetric=GPG_CIPHER,
                               armor=False,
                               always_trust=True, passphrase=key)
        return msg.data[6:]
Exemplo n.º 21
0
def deciphersteg(stegdata, cipher, key, aesmode, verbose=False, unprep=True):
# Decipher hidden message from array of data hidden in JT65 errors
    stegedmsg = ""
    stegedmsgba = np.array(range(0), dtype=np.int32)
    statusar = []

    for index, value in enumerate(stegdata):
        if unprep:
            value = jt.unprepsteg(value)  # Decode real data from FEC

        if cipher == "none":
            recoveredtext = jt.decode(value)[0:13]
            if verbose:
                print "Steg Text in Message " + str(index) + " : " + recoveredtext
            stegedmsg += recoveredtext

        elif cipher == "XOR" or cipher == "OTP":
            thesebytes = jt65tobytes(value)

            thisstatus = thesebytes[0:1]

            if thisstatus & 0x40 == 0x40:
                # This is the last packet, signals how many bytes to read
                bytestoread = thisstatus & 0x3F
                thisunstegbytes = thesebytes[1:bytestoread + 1]
            else:
                thisunstegbytes = thesebytes[1:]

            if verbose:
                print "Steg Data in Message " + str(index) + " : " + str(thisunstegbytes)
            stegedmsgba = np.append(stegedmsgba, thisunstegbytes)

        else:
            thesebytes = jt65tobytes(value)
            thisunstegbytes = thesebytes[1:10]

            if verbose:
                print "Steg Data in Message " + str(index) + " : " + str(thisunstegbytes)
            stegedmsgba = np.append(stegedmsgba, thisunstegbytes)

    if cipher == "XOR":
        if verbose:
            print"Cipher Data : " + str(stegedmsgba)

        finalcipherdata = (
            ''.join('{0:02x}'.format(int(e)).decode("hex") for e in stegedmsgba))

        if verbose:
            print"Cipher Data Hex : " + finalcipherdata

        cryptobj = XOR.new(key)
        stegedmsg = cryptobj.decrypt(finalcipherdata)

    if cipher == "ARC4":
        if verbose:
            print"Cipher Data : " + str(stegedmsgba)

        finalcipherdata = (
            ''.join('{0:02x}'.format(int(e)).decode("hex") for e in stegedmsgba))

        if verbose:
            print"Cipher Data Hex : " + finalcipherdata

        tempkey = SHA.new(key).digest()
        cryptobj = ARC4.new(tempkey)
        stegedmsg = cryptobj.decrypt(finalcipherdata)

    if cipher == "AES":
        if verbose:
            print"Cipher Data : " + str(stegedmsgba)

        finalcipherdata = (
            ''.join('{0:02x}'.format(int(e)).decode("hex") for e in stegedmsgba))

        if verbose:
            print"Cipher Data Hex : " + finalcipherdata

        if aesmode == "ECB":
            cryptobj = AES.new(key, AES.MODE_ECB)
        elif aesmode == "CBC":
            cryptobj = AES.new(key, AES.MODE_CBC, finalcipherdata[0:16])
            finalcipherdata = finalcipherdata[16:]
        elif aesmode == "CFB":
            cryptobj = AES.new(key, AES.MODE_CFB, finalcipherdata[0:16])
            finalcipherdata = finalcipherdata[16:]

        stegedmsg = cryptobj.decrypt(finalcipherdata)

    if cipher == "GPG":
        if verbose:
            print"Cipher Data : " + str(stegedmsgba)

        finalcipherdata = (
            ''.join('{0:02x}'.format(int(e)).decode("hex") for e in stegedmsgba))

        if verbose:
            print"Cipher Data Hex : " + finalcipherdata

        gpg = GPG()
        stegedmsg = gpg.decrypt(finalcipherdata)
        stegedmsg = str(stegedmsg)

    if cipher == "OTP":
        finalcipherdata = (''.join(chr(e) for e in stegedmsgba))

        if verbose:
            print"Cipher Data : " + str(finalcipherdata)

        stegedmsg = otp_decode(str(finalcipherdata), key)

    return stegedmsg