Exemplo n.º 1
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
Exemplo n.º 2
0
 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'))
Exemplo n.º 3
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)
Exemplo n.º 4
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)
Exemplo n.º 5
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())
    def test_delete(self, mock_error_handler, mock_context_unpack):
        response = self.app.delete('/tenders/abc/dump', status=403)
        self.assertEqual(response.status, '403 Forbidden')
        self.app.authorization = ('Basic', ('archivarius', ''))
        response = self.app.delete('/tenders/abc/dump')

        encrypted_dump = response.json['data']['tender']
        box = SecretBox('a' * 32)
        decrypted_data = box.decrypt(b64decode(encrypted_dump))
        decrypted_data = json.loads(decrypted_data)
        self.assertEqual(response.status, '200 OK')
        self.assertEqual(decrypted_data, tender.serialize.return_value)
Exemplo n.º 7
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')
Exemplo n.º 8
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')
 def test_dump_resource(self):
     request = MagicMock()
     context = {
         'id': uuid.uuid4().hex,
         'rev': '1-{}'.format(uuid.uuid4().hex),
         'dateModified': datetime.now().isoformat(),
         'doc_type': 'Tenders'
     }
     request.registry.docservice_key.vk = 'a' * 32
     request.context.serialize.return_value = context
     res = dump_resource(request)
     box = SecretBox('a' * 32)
     decrypted_data = box.decrypt(b64decode(res))
     decrypted_data = json.loads(decrypted_data)
     self.assertNotEqual(res, json.dumps(context))
     self.assertEqual(decrypted_data, context)
Exemplo n.º 10
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
Exemplo n.º 11
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)
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)
Exemplo n.º 14
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)
Exemplo n.º 15
0
    def __init__(self):
        libnacl = nacl = None
        try:
            import libnacl
        except ImportError:
            try:
                import nacl
            except ImportError:
                raise ImportError(
                    'Either libnacl or pynacl module'
                    ' is required for this tool, neither one can be imported.')

        if libnacl:
            from libnacl.secret import SecretBox
            self.nonce_size = libnacl.crypto_secretbox_NONCEBYTES
            self.key_size = libnacl.crypto_secretbox_KEYBYTES
            self.key_encode = lambda key: b64_encode(key.sk)
            self.key_decode = lambda key_str, raw=False:\
             SecretBox(key_str if raw else b64_decode(key_str))
            self.random = libnacl.randombytes
            self.error = ValueError

        if nacl:
            import warnings
            with warnings.catch_warnings(record=True):  # cffi warnings
                from nacl.exceptions import CryptoError
                from nacl.encoding import RawEncoder, URLSafeBase64Encoder
                from nacl.secret import SecretBox
                from nacl.utils import random
            self.nonce_size = SecretBox.NONCE_SIZE
            self.key_size = SecretBox.KEY_SIZE
            self.key_encode = lambda key: key.encode(URLSafeBase64Encoder
                                                     ).decode().strip()
            self.key_decode = lambda key_str, raw=False:\
             SecretBox(key_str, URLSafeBase64Encoder if not raw else RawEncoder)
            self.random = random
            self.error = CryptoError
Exemplo n.º 16
0
 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'))
Exemplo n.º 17
0
def _send_request(looper, helpers, fees, wallets_count, address, owner,
                  sdk_wallet_trustee, sdk_wallet_trustees, sdk_wallet_stewards,
                  sdk_wallet_clients, sdk_wallet_trust_anchors):
    print(wallets_count)
    wallets = sdk_wallet_trustees[:wallets_count.get(TRUSTEE, 0)] + \
              sdk_wallet_stewards[:wallets_count.get(STEWARD, 0)] + \
              sdk_wallet_clients[:wallets_count.get(IDENTITY_OWNER, 0)] + \
              sdk_wallet_trust_anchors[:wallets_count.get(TRUST_ANCHOR, 0)]
    # prepare owner parameter
    if owner == TRUSTEE:
        sender_wallet = sdk_wallet_trustees[0]
    elif owner == STEWARD:
        sender_wallet = sdk_wallet_stewards[0]
    elif owner == IDENTITY_OWNER:
        sender_wallet = sdk_wallet_clients[0]
    elif owner == TRUST_ANCHOR:
        sender_wallet = sdk_wallet_trust_anchors[0]
    else:
        sender_wallet = wallets[0]
    target_dest = sdk_wallet_trustee[1] if owner == "-1" else sender_wallet[1]

    # prepare data
    data = SecretBox().encrypt(json.dumps({'name': 'Jaime'}).encode()).hex()

    # create request
    request = add_attribute(looper, sender_wallet, None, target_dest, enc=data)
    request = sdk_json_to_request_object(json.loads(request))

    request.signature = None
    request.signatures = None
    # add fees
    request = add_fees_request_with_address(helpers, fees, request, address)
    # sign request
    request = sdk_multi_sign_request_objects(looper, wallets, [request])

    return helpers.sdk.sdk_send_and_check(request)
Exemplo n.º 18
0
 def decrypt(ciphertext, key):
     """Decrypt ciphertext using key."""
     return SecretBox(key).decrypt(ciphertext)
 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)
Exemplo n.º 20
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
Exemplo n.º 22
0
 def _extract_caveat_key(self, signature, caveat):
     key = truncate_or_pad(signature)
     box = SecretBox(key=key)
     decrypted = box.decrypt(caveat._verification_key_id)
     return decrypted
 def decrypt(self, signature, field_data):
     key = truncate_or_pad(signature)
     box = SecretBox(key=key)
     encoded = convert_to_bytes(field_data[len(self.signifier):])
     decrypted = box.decrypt(standard_b64decode(encoded))
     return convert_to_string(decrypted)
Exemplo n.º 24
0
 def _extract_caveat_key(self, signature, caveat):
     key = truncate_or_pad(signature)
     box = SecretBox(key=key)
     decrypted = box.decrypt(caveat._verification_key_id)
     return decrypted
Exemplo n.º 25
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
Exemplo n.º 26
0
    if net["name"] == netname:
        netid = net["id"]
        print("Got network id: %s" % netid, file=sys.stderr)
        break

#Get the client's hostid and decrypt it.
to_read = int.from_bytes(sys.stdin.buffer.read(1), byteorder='big')
hkdf_salt=b''
while len(hkdf_salt) < to_read:
    hkdf_salt += sys.stdin.buffer.read(to_read - len(hkdf_salt))
to_read = int.from_bytes(sys.stdin.buffer.read(1), byteorder='big')
ciphertext=b''
while len(ciphertext) < to_read:
    ciphertext += sys.stdin.buffer.read(to_read - len(ciphertext))

to_server_key = get_subkey("to_server", hkdf_salt)
hostid = SecretBox(to_server_key).decrypt(ciphertext).decode()
print("Get hostid %s from client" % hostid, file=sys.stderr)

#Now authorize the client
print("Authorizing", file=sys.stderr)
zt_post("controller/network/%s/member/%s" % (netid, hostid),
            { 'authorized': True, 'activeBridge': True })

#Encrypt and send back the network id.
from_server_key = get_subkey("from_server", hkdf_salt)
ciphertext = SecretBox(from_server_key).encrypt(netid.encode())
assert(len(ciphertext) < 256)
sys.stdout.buffer.write(len(ciphertext).to_bytes(1, byteorder='big') + ciphertext)
print("Finished", file=sys.stderr)
Exemplo n.º 27
0
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)