def add_third_party_caveat(self,
                            macaroon,
                            location,
                            key,
                            key_id,
                            **kwargs):
     derived_key = truncate_or_pad(
         generate_derived_key(convert_to_bytes(key))
     )
     old_key = truncate_or_pad(binascii.unhexlify(macaroon.signature_bytes))
     box = SecretBox(key=old_key)
     verification_key_id = box.encrypt(
         derived_key, nonce=kwargs.get('nonce')
     )
     caveat = Caveat(
         caveat_id=key_id,
         location=location,
         verification_key_id=verification_key_id
     )
     macaroon.caveats.append(caveat)
     encode_key = binascii.unhexlify(macaroon.signature_bytes)
     macaroon.signature = sign_third_party_caveat(
         encode_key,
         caveat._verification_key_id,
         caveat._caveat_id
     )
     return macaroon
Beispiel #2
0
def dump_resource(request):
    docservice_key = getattr(request.registry, 'docservice_key', None)
    box = SecretBox(docservice_key.vk)
    data = request.context.serialize()
    json_data = dumps(data)
    encrypted_data = box.encrypt(json_data)
    return b64encode(encrypted_data)
Beispiel #3
0
def test_attrib_with_enc_passes():
    secretBox = SecretBox()
    enc_data = secretBox.encrypt(json.dumps({'name': 'Alice'}).encode()).hex()

    msg = {
        TXN_TYPE: ATTRIB,
        TARGET_NYM: VALID_TARGET_NYM,
        ENC: enc_data
    }
    validator.validate(msg)
Beispiel #4
0
def testSendAttribSucceedsForNonEmptyEnc(
        looper, sdk_pool_handle, sdk_wallet_trustee):
    raw = json.dumps({
        'name': 'Alice'
    })
    secretBox = SecretBox()

    new_wallet = sdk_add_new_nym(looper, sdk_pool_handle, sdk_wallet_trustee)
    parameters = None
    sdk_add_attribute_and_check(looper, sdk_pool_handle, new_wallet, parameters,
                                enc=secretBox.encrypt(raw.encode()).hex())
Beispiel #5
0
def testSendAttribHasInvalidSyntaxIfRawAndEncPassedAtSameTime(
        looper, sdk_pool_handle, sdk_wallet_trustee):
    raw = json.dumps({
        'name': 'Alice'
    })
    secretBox = SecretBox()

    new_wallet = sdk_add_new_nym(looper, sdk_pool_handle, sdk_wallet_trustee)
    parameters = None
    with pytest.raises(RequestNackedException) as e:
        sdk_add_attribute_and_check(looper, sdk_pool_handle, new_wallet, parameters,
                                    xhash=secretBox.encrypt(raw.encode()).hex(), enc=raw)
    e.match('not a valid hash')
Beispiel #6
0
def testSendAttribHasInvalidSyntaxIfRawHashAndEncPassedAtSameTime(
        looper, sdk_pool_handle, sdk_wallet_trustee):
    raw = json.dumps({
        'name': 'Alice'
    })

    secretBox = SecretBox()
    encryptedRaw = secretBox.encrypt(raw.encode())
    new_wallet = sdk_add_new_nym(looper, sdk_pool_handle, sdk_wallet_trustee)
    parameters = raw
    with pytest.raises(RequestNackedException) as e:
        sdk_add_attribute_and_check(looper, sdk_pool_handle, new_wallet, parameters,
                                    xhash=sha256(encryptedRaw).hexdigest(), enc=encryptedRaw.hex())
    e.match('only one field from raw, enc, hash is expected')
Beispiel #7
0
 def add_third_party_caveat(self, macaroon, location, key, key_id,
                            **kwargs):
     derived_key = truncate_or_pad(
         generate_derived_key(convert_to_bytes(key)))
     old_key = truncate_or_pad(binascii.unhexlify(macaroon.signature_bytes))
     box = SecretBox(key=old_key)
     verification_key_id = box.encrypt(derived_key,
                                       nonce=kwargs.get('nonce'))
     caveat = Caveat(caveat_id=key_id,
                     location=location,
                     verification_key_id=verification_key_id)
     macaroon.caveats.append(caveat)
     encode_key = binascii.unhexlify(macaroon.signature_bytes)
     macaroon.signature = sign_third_party_caveat(
         encode_key, caveat._verification_key_id, caveat._caveat_id)
     return macaroon
Beispiel #8
0
def testSendAttribSucceedsForNonEmptyEnc(be, do, poolNodesStarted, trusteeCli):

    uuidIdentifier = createUuidIdentifier()
    addNym(be, do, trusteeCli, idr=uuidIdentifier)

    raw = json.dumps({'name': 'Alice'})

    secretBox = SecretBox()

    parameters = {
        'dest': uuidIdentifier,
        'enc': secretBox.encrypt(raw.encode()).hex()
    }

    be(trusteeCli)
    do('send ATTRIB dest={dest} enc={enc}',
       mapper=parameters,
       expect=ATTRIBUTE_ADDED,
       within=2)
def testSendAttribSucceedsForNonEmptyEnc(
        be, do, poolNodesStarted, trusteeCli):

    uuidIdentifier = createUuidIdentifier()
    addNym(be, do, trusteeCli, idr=uuidIdentifier)

    raw = json.dumps({
        'name': 'Alice'
    })

    secretBox = SecretBox()

    parameters = {
        'dest': uuidIdentifier,
        'enc': secretBox.encrypt(raw.encode()).hex()
    }

    be(trusteeCli)
    do('send ATTRIB dest={dest} enc={enc}',
       mapper=parameters, expect=ATTRIBUTE_ADDED, within=2)
Beispiel #10
0
def testSendAttribHasInvalidSyntaxIfRawAndEncPassedAtSameTime(
        be, do, poolNodesStarted, trusteeCli):

    uuidIdentifier = createUuidIdentifier()
    addNym(be, do, trusteeCli, idr=uuidIdentifier)

    raw = json.dumps({'name': 'Alice'})

    secretBox = SecretBox()

    parameters = {
        'dest': uuidIdentifier,
        'raw': raw,
        'enc': secretBox.encrypt(raw.encode()).hex()
    }

    be(trusteeCli)
    do('send ATTRIB dest={dest} raw={raw} enc={enc}',
       mapper=parameters,
       expect=INVALID_SYNTAX,
       within=2)
def testSendAttribHasInvalidSyntaxIfRawAndEncPassedAtSameTime(
        be, do, poolNodesStarted, trusteeCli):

    uuidIdentifier = createUuidIdentifier()
    addNym(be, do, trusteeCli, idr=uuidIdentifier)

    raw = json.dumps({
        'name': 'Alice'
    })

    secretBox = SecretBox()

    parameters = {
        'dest': uuidIdentifier,
        'raw': raw,
        'enc': secretBox.encrypt(raw.encode()).hex()
    }

    be(trusteeCli)
    do('send ATTRIB dest={dest} raw={raw} enc={enc}',
       mapper=parameters, expect=INVALID_SYNTAX, within=2)
Beispiel #12
0
class Console(object):
    def __init__(self, key=None, host='127.0.0.1', port=5199, have_sodium=HAVE_SODIUM, merge_nonces=False):
        if have_sodium:
            if key:
                key = base64.b64decode(key)
            else:
                # libnacl won't like it if you send anything less then KEYBYTES
                key = '\0' * libnacl.crypto_secretbox_KEYBYTES
            self.__merge_nonces = merge_nonces
            self.__box = SecretBox(key=key)
            self.__my_nonce = rand_nonce()
        else:
            self.__box = None
            self.__my_nonce = '\0'
        self.__client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        logging.info('Connecting to %s:%d' % (host, port))
        self.__client.connect((host, port))
        logging.debug('Sending my nonce: %s' % self.__my_nonce.encode('hex'))
        self.__client.send(self.__my_nonce)
        if self.__box:
            self.__th_nonce = self.__client.recv(libnacl.crypto_secretbox_NONCEBYTES)
        else:
            self.__th_nonce = self.__client.recv(1)
        logging.debug('Got their nonce: %s' % self.__th_nonce.encode('hex'))

    @staticmethod
    def increment_nonce(nonce):
        count = unpack("!I", nonce[0:4])[0]
        count += 1
        return pack("!I", count) + nonce[4:]

    def _send(self, msg):
        self.__client.send(pack("!I", len(msg)))
        self.__client.send(msg)

    def _recvbits(self, bits):
        data = self.__client.recv(bits)
        while len(data) < bits:
            data += self.__client.recv(bits - len(data))
        return data

    def _recv(self):
        bits = self._recvbits(4)
        length = unpack("!I", bits)[0]
        logging.debug('Got length of %d' % length)
        return self._recvbits(length)

    def _reading_nonce(self):
        if self.__merge_nonces:
            half_nonce_size = len(self.__my_nonce) / 2
            return self.__my_nonce[0:half_nonce_size] + self.__th_nonce[half_nonce_size:]
        else:
            return self.__th_nonce

    def _writing_nonce(self):
        if self.__merge_nonces:
            half_nonce_size = len(self.__my_nonce) / 2
            return self.__th_nonce[0:half_nonce_size] + self.__my_nonce[half_nonce_size:]
        else:
            return self.__my_nonce

    def disconnect(self):
        self.__client.close()

    def execute(self, msg):
        logging.info("Sending: %s" % msg)
        if self.__box:
            msg = self.__box.encrypt(msg, nonce=self._writing_nonce(), pack_nonce=False)[1]
            logging.info("Cipher text: %s" % msg.encode('hex'))
        self._send(msg)

        logging.info("Waiting for response...")
        msg = self._recv()
        if self.__box:
            logging.info("Cipher text: %s" % msg.encode('hex'))
            msg = self.__box.decrypt(msg, nonce=self._reading_nonce())
            self.__my_nonce = Console.increment_nonce(self.__my_nonce)
            logging.debug('Our new nonce: %s' % self.__my_nonce.encode('hex'))
            self.__th_nonce = Console.increment_nonce(self.__th_nonce)
            logging.debug('Their new nonce: %s' % self.__th_nonce.encode('hex'))
        logging.info("Received: %s" % msg)
        return msg
from indy.ledger import build_get_attrib_request
from libnacl.secret import SecretBox
from hashlib import sha256

from plenum.common.exceptions import RequestNackedException

from plenum.test.helper import sdk_get_and_check_replies

from indy_node.test.helper import createUuidIdentifier, sdk_add_attribute_and_check, \
    sdk_get_attribute_and_check, modify_field
from plenum.test.pool_transactions.helper import sdk_sign_and_send_prepared_request

attrib_name = 'dateOfBirth'

secretBox = SecretBox()
enc_data = secretBox.encrypt(json.dumps({'name': 'Alice'}).encode()).hex()
hash_data = sha256(json.dumps({'name': 'Alice'}).encode()).hexdigest()


@pytest.fixture(scope="module")
def send_raw_attrib(looper, sdk_pool_handle, sdk_wallet_trustee):
    rep = sdk_add_attribute_and_check(
        looper, sdk_pool_handle, sdk_wallet_trustee,
        json.dumps({attrib_name: {
            'dayOfMonth': 23,
            'year': 1984,
            'month': 5
        }}))

    return rep
import pytest
import json

from libnacl.secret import SecretBox
from hashlib import sha256

from indy_client.test.cli.constants import INVALID_SYNTAX
from indy_client.test.cli.helper import createUuidIdentifier, addNym


attrib_name = 'dateOfBirth'

secretBox = SecretBox()
enc_data = secretBox.encrypt(json.dumps({'name': 'Alice'}).encode()).hex()
hash_data = sha256(json.dumps({'name': 'Alice'}).encode()).hexdigest()

FOUND_ATTRIBUTE = 'Found attribute'
ATTRIBUTE_ADDED = 'Attribute added for nym {valid_dest}'
RETURNED_RAW_DATA = [FOUND_ATTRIBUTE, attrib_name, 'dayOfMonth', 'year', 'month']
RETURNED_ENC_DATA = [FOUND_ATTRIBUTE, enc_data]
RETURNED_HASH_DATA = [FOUND_ATTRIBUTE, hash_data]
ATTR_NOT_FOUND = 'Attr not found'


@pytest.fixture(scope="module")
def send_raw_attrib(be, do, poolNodesStarted, trusteeCli):

    valid_identifier = createUuidIdentifier()
    invalid_identifier = createUuidIdentifier()
    addNym(be, do, trusteeCli, idr=valid_identifier)
Beispiel #15
0
class Console(object):
    def __init__(self,
                 key=None,
                 host='127.0.0.1',
                 port=5199,
                 have_sodium=HAVE_SODIUM):
        if have_sodium:
            if key:
                key = base64.b64decode(key)
            else:
                # libnacl won't like it if you send anything less then KEYBYTES
                key = '\0' * libnacl.crypto_secretbox_KEYBYTES
            self.__box = SecretBox(key=key)
            self.__my_nonce = rand_nonce()
        else:
            self.__box = None
            self.__my_nonce = '\0'
        self.__client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        logging.info('Connecting to %s:%d' % (host, port))
        self.__client.connect((host, port))
        logging.debug('Sending my nonce: %s' % self.__my_nonce.encode('hex'))
        self.__client.send(self.__my_nonce)
        if self.__box:
            self.__th_nonce = self.__client.recv(
                libnacl.crypto_secretbox_NONCEBYTES)
        else:
            self.__th_nonce = self.__client.recv(1)
        logging.debug('Got their nonce: %s' % self.__th_nonce.encode('hex'))

    @staticmethod
    def increment_nonce(nonce):
        count = unpack("!I", nonce[0:4])[0]
        count += 1
        return pack("!I", count) + nonce[4:]

    def _send(self, msg):
        self.__client.send(pack("!I", len(msg)))
        self.__client.send(msg)

    def _recvbits(self, bits):
        data = self.__client.recv(bits)
        while len(data) < bits:
            data += self.__client.recv(bits - len(data))
        return data

    def _recv(self):
        bits = self._recvbits(4)
        length = unpack("!I", bits)[0]
        logging.debug('Got length of %d' % length)
        return self._recvbits(length)

    def disconnect(self):
        self.__client.close()

    def execute(self, msg):
        logging.info("Sending: %s" % msg)
        if self.__box:
            msg = self.__box.encrypt(msg,
                                     nonce=self.__my_nonce,
                                     pack_nonce=False)[1]
            logging.info("Cipher text: %s" % msg.encode('hex'))
            self.__my_nonce = Console.increment_nonce(self.__my_nonce)
            logging.debug('New nonce: %s' % self.__my_nonce.encode('hex'))
        self._send(msg)

        logging.info("Waiting for response...")
        msg = self._recv()
        if self.__box:
            logging.info("Cipher text: %s" % msg.encode('hex'))
            msg = self.__box.decrypt(msg, nonce=self.__th_nonce)
            self.__th_nonce = Console.increment_nonce(self.__th_nonce)
            logging.debug('New nonce: %s' % self.__th_nonce.encode('hex'))
        logging.info("Received: %s" % msg)
        return msg
 def encrypt(self, signature, field_data):
     encrypt_key = truncate_or_pad(signature)
     box = SecretBox(key=encrypt_key)
     encrypted = box.encrypt(convert_to_bytes(field_data), nonce=self.nonce)
     return self._signifier + standard_b64encode(encrypted)