Example #1
0
def make_peer_data(workers, listeners):
    peer_data = [config.PROTOCOL_MAGIC, [0, 1, 0], {}, {}]
    for cls in workers:
        peer_data[3][cls.message_type] = [
            0,
            cbor.Tag(24, cbor.dumps(MessageSndRcv[cls.message_type]))]
    for msgtype in listeners.keys():
        peer_data[2][msgtype] = [0, cbor.Tag(24, cbor.dumps(MessageSndRcv[msgtype]))]
    return peer_data
Example #2
0
 def encode(self):
     """
     Encodes the message into a CBOR array with the appropriate cbor tag attached
     :return: COSE message
     """
     return cbor.dumps(
         cbor.Tag(self.cbor_tag, [self.encoded_protected_header, self.unprotected_header, self.payload, self.signature]))
Example #3
0
    def to_dict(self):
        '''Dump a feature collection's features to a dictionary.

        This does not include additional data, such as whether
        or not the collection is read-only.  The returned dictionary
        is suitable for serialization into JSON, CBOR, or similar
        data formats.

        '''
        def is_non_native_sc(ty, encoded):
            return (ty == 'StringCounter'
                    and not is_native_string_counter(encoded))

        fc = {}
        native = ('StringCounter', 'Unicode')
        for name, feat in self._features.iteritems():
            if name.startswith(self.EPHEMERAL_PREFIX):
                continue
            if not isinstance(name, unicode):
                name = name.decode('utf-8')
            tyname = registry.feature_type_name(name, feat)
            encoded = registry.get(tyname).dumps(feat)

            # This tomfoolery is to support *native untagged* StringCounters.
            if tyname not in native or is_non_native_sc(tyname, encoded):
                encoded = cbor.Tag(cbor_names_to_tags[tyname], encoded)
            fc[name] = encoded
        return fc
Example #4
0
    def __repr__(self):
        repr = cbor.loads(cbor.dumps(cbor.Tag(self.cbor_tag,
                                              [self.encoded_protected_header, self.encoded_unprotected_header,
                                               self.payload, self.auth_tag])))
        t = repr.tag
        v = [binascii.hexlify(element) if isinstance(element, bytes) else element for element in repr.value]

        return str((t, v))
Example #5
0
    def encode(self):
        """Encodes the message into a CBOR array with the correct CBOR tag."""

        if len(binascii.hexlify(self.auth_tag)) not in [16, 32, 64, 96, 128]:
            raise CoseInvalidTag("The length of the COSE auth tag must be in [16, 32, 64, 96, 128]")

        return cbor.dumps(cbor.Tag(self.cbor_tag,
                                   [self.encoded_protected_header, self.encoded_unprotected_header, self.payload,
                                    self.auth_tag]))
Example #6
0
 def encode(self):
     """
     Encodes the message into a CBOR array
     :return: COSE message
     """
     return cbor.dumps(
         cbor.Tag(self.cbor_tag, [
             self.encoded_protected_header, self.unprotected_header,
             self.payload, self.signers
         ]))
Example #7
0
    def encode(self):
        """Encodes the message into a CBOR array"""

        if len(binascii.hexlify(self.auth_tag)) not in [16, 32, 64, 96, 128]:
            raise ValueError("Tag has invalid size.")

        return cbor.dumps(
            cbor.Tag(self.cbor_tag, [
                self.encoded_protected_header, self.unprotected_header,
                self.payload, self.encoded_recipients
            ]))
Example #8
0
def signWrapper(algo, private_key, public_key, encwrapper):
    wrapper = cbor.loads(encwrapper)

    COSE_Sign = copy.deepcopy(wrapper[1])
    if not COSE_Sign:
        protected = cbor.dumps({
            3: APPLICATION_OCTET_STREAM_ID,  # Content Type
        })
        unprotected = {}
        signatures = []
        # Create a COSE_Sign_Tagged object
        COSE_Sign = [protected, unprotected, None, signatures]

    if algo == EDDSA:
        public_bytes = public_key.to_bytes()
    else:
        public_bytes = public_key.public_bytes(
            serialization.Encoding.DER,
            serialization.PublicFormat.SubjectPublicKeyInfo)

    # NOTE: Using RFC7093, Method 4
    digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
    digest.update(public_bytes)
    kid = digest.finalize()
    # Sign the payload
    protected = cbor.dumps({
        1: algo,  # alg
    })  # Create the signing object
    unprotected = {
        4: kid  #kid
    }

    Sig_structure = [
        "Signature",  # Context
        COSE_Sign[0],  # Body Protected
        protected,  # signature protected
        b'',  # External AAD
        wrapper[2]  # payload
    ]
    sig_str = cbor.dumps(Sig_structure, sort_keys=True)

    if algo == EDDSA:
        signature = private_key.sign(sig_str)
    else:
        signature = private_key.sign(sig_str, ec.ECDSA(hashes.SHA256()))

    COSE_Signature = [protected, unprotected, signature]
    COSE_Sign[3].append(COSE_Signature)
    wrapper[1] = cbor.Tag(COSE_Sign_Tag, COSE_Sign)
    return wrapper
Example #9
0
def _get_conditions(args):
    conds = []
    uuid_vendor = None
    if args.vendorname:
        uuid_vendor = uuid.uuid5(uuid.NAMESPACE_DNS, str(args.vendorname))
        print("Vendor ID: {}".format(uuid_vendor.hex))
        conds.append([CONDITION_VENDORID, uuid_vendor.bytes])
        if args.classname:
            uuid_class = uuid.uuid5(uuid_vendor, args.classname)
            conds.append([CONDITION_CLASSID, uuid_class.bytes])
            print("Class ID: {}".format(uuid_class.hex))
            if args.deviceid:
                conds.append(
                    [CONDITION_DEVICEID,
                     binascii.unhexlify(args.deviceid)])
    if args.valid_duration:

        timestamp = cbor.dumps(
            cbor.Tag(1,
                     _get_timestamp() + args.valid_duration))
        conds.append([CONDITION_BESTBEFORE, timestamp])
    return conds
Example #10
0
addrType = 0
addrAttributes = {}
addrRoot = [
        addrType,
        [ addrType, xpub ],
        addrAttributes
        ]

addrRoot = cbor.dumps(addrRoot)
print("addrRoot:", addrRoot.hex())

sha3 = hashlib.sha3_256(addrRoot)
print("SHA3:", sha3.hexdigest())

addrRoot = hashlib.blake2b(sha3.digest(), digest_size=28)
print("Blake2b:", addrRoot.hexdigest())

abstractHash = addrRoot.digest()
address = [
        abstractHash,
        addrAttributes,
        addrType
        ]
address = cbor.dumps(address)
crc = binascii.crc32(address)
taggedAddress = cbor.Tag(24, address)
cwid = cbor.dumps([taggedAddress, crc])
cwid = base58.b58encode(cwid)
print("CwID:", cwid.decode(), "\n")
def get_cwid_from_mnemonic(words):

    # print("\nMnemonic:", words)

    entropy = Mnemonic('english').to_entropy(words)
    # print("Entropy:", entropy.hex())

    cborEnt = cbor.dumps(bytes(entropy))
    # print("Serialised:", cborEnt.hex(), "\n")

    seed = hashlib.blake2b(cborEnt, digest_size=32)
    # print("Seed:", seed.hexdigest())

    cborSeed = cbor.dumps(seed.digest())
    # print("Serialised:", cborSeed.hex(), "\n")

    passPhrase = ''
    # print("Spending pass:"******"Serialised:", passPhrase.hex())

    seedBuf = cbor.dumps(cborSeed)

    hashedSeed = hashlib.blake2b(seedBuf, digest_size=32)
    salt = cbor.dumps(hashedSeed.digest())
    # print("Salt:", salt.hex())

    hashedPass = scrypt.hash(passPhrase, salt, buflen=32)
    # print("Pass:"******"14|8|1|" + base64.standard_b64encode(hashedPass).decode() + "|" + base64.standard_b64encode(
        salt).decode()
    encryptedPass = cbor.dumps(encryptedPass.encode('utf-8'))
    # print("Encrypted Pass:"******"Base64-ed:", base64.standard_b64encode(encryptedPass).decode(), "\n")

    for i in range(5, 1000):
        buf = hmac.new(cborSeed, b'Root Seed Chain %d' % i, hashlib.sha512).digest()
        buf_l, buf_r = buf[:32], buf[32:]
        if hashlib.sha512(buf_l).digest()[31] & 32 == 0:
            # print(b'Root Seed Chain %d' % i)
            bip32 = ed25519.SigningKey(buf_l)
            break

    # print("SecretKey:", buf_l.hex())
    # print("ChainCode:", buf_r.hex())

    xpub = bip32.vk_s + buf_r
    # print("XPub:", xpub.hex())

    addrType = 0
    addrAttributes = {}
    addrRoot = [
        addrType,
        [addrType, xpub],
        addrAttributes
    ]

    addrRoot = cbor.dumps(addrRoot)
    # print("addrRoot:", addrRoot.hex())

    sha3 = hashlib.sha3_256(addrRoot)
    # print("SHA3:", sha3.hexdigest())

    addrRoot = hashlib.blake2b(sha3.digest(), digest_size=28)
    # print("Blake2b:", addrRoot.hexdigest())

    abstractHash = addrRoot.digest()
    address = [
        abstractHash,
        addrAttributes,
        addrType
    ]
    address = cbor.dumps(address)
    crc = binascii.crc32(address)
    taggedAddress = cbor.Tag(24, address)
    cwid = cbor.dumps([taggedAddress, crc])
    cwid = base58.b58encode(cwid)
    # print("CwID:", cwid.decode(), "\n")
    return cwid.decode()
Example #12
0
digest.update(
    public_key.public_bytes(serialization.Encoding.DER,
                            serialization.PublicFormat.SubjectPublicKeyInfo))
kid = digest.finalize()
# Sign the payload
protected = cbor.dumps({
    1: ES256,  # alg
    4: kid  #kid
})

unprotected = {}
Sig_structure = [
    "Signature",  # Context
    COSE_Sign[0],  # Body Protected
    protected,  # signature protected
    b'',  # External AAD
    COSE_Sign[2]
]

sig_str = cbor.dumps(Sig_structure)

signature = private_key.sign(sig_str, ec.ECDSA(hashes.SHA256()))

COSE_Signature = [protected, unprotected, signature]

COSE_Sign[3].append(COSE_Signature)

with open(sys.argv[4], 'wb') as fd:
    COSE_Sign_Tagged = cbor.Tag(98, COSE_Sign)
    fd.write(cbor.dumps(COSE_Sign_Tagged))
Example #13
0
if __name__ == '__main__':
    from . import config
    ep = Transport().endpoint()  # Unaddressable transport.
    # ep = Transport(('127.0.0.1', 3000)).endpoint()
    print('connect')
    conn = ep.connect(config.CLUSTER_ADDR)

    # cardano node handshake.
    # send peer data.

    DEFAULT_PEER_DATA = [
        764824073,  # protocol magic.
        [0, 1, 0],  # version
        {
            0x04: [0, cbor.Tag(24, cbor.dumps(0x05))],
            0x05: [0, cbor.Tag(24, cbor.dumps(0x04))],
            0x06: [0, cbor.Tag(24, cbor.dumps(0x07))],
            0x22: [0, cbor.Tag(24, cbor.dumps(0x5e))],
            0x25: [0, cbor.Tag(24, cbor.dumps(0x5e))],
            0x2b: [0, cbor.Tag(24, cbor.dumps(0x5d))],
            0x31: [0, cbor.Tag(24, cbor.dumps(0x5c))],
            0x37: [0, cbor.Tag(24, cbor.dumps(0x62))],
            0x3d: [0, cbor.Tag(24, cbor.dumps(0x61))],
            0x43: [0, cbor.Tag(24, cbor.dumps(0x60))],
            0x49: [0, cbor.Tag(24, cbor.dumps(0x5f))],
            0x53: [0, cbor.Tag(24, cbor.dumps(0x00))],
            0x5c: [0, cbor.Tag(24, cbor.dumps(0x31))],
            0x5d: [0, cbor.Tag(24, cbor.dumps(0x2b))],
            0x5e: [0, cbor.Tag(24, cbor.dumps(0x25))],
            0x5f: [0, cbor.Tag(24, cbor.dumps(0x49))],
Example #14
0
        #0x31:  [0, cbor.Tag(24, cbor.dumps(0x5c))],
        #0x37:  [0, cbor.Tag(24, cbor.dumps(0x62))],
        #0x3d:  [0, cbor.Tag(24, cbor.dumps(0x61))],
        #0x43:  [0, cbor.Tag(24, cbor.dumps(0x60))],
        #0x49:  [0, cbor.Tag(24, cbor.dumps(0x5f))],
        #0x53:  [0, cbor.Tag(24, cbor.dumps(0x00))],
        #0x5c:  [0, cbor.Tag(24, cbor.dumps(0x31))],
        #0x5d:  [0, cbor.Tag(24, cbor.dumps(0x2b))],
        #0x5e:  [0, cbor.Tag(24, cbor.dumps(0x25))],
        #0x5f:  [0, cbor.Tag(24, cbor.dumps(0x49))],
        #0x60:  [0, cbor.Tag(24, cbor.dumps(0x43))],
        #0x61:  [0, cbor.Tag(24, cbor.dumps(0x3d))],
        #0x62:  [0, cbor.Tag(24, cbor.dumps(0x37))],
    },
    { # clients, send msg code -> recv msg code.
        Message.GetHeaders:     [0, cbor.Tag(24, cbor.dumps(Message.Headers))],
        Message.Headers:        [0, cbor.Tag(24, cbor.dumps(Message.GetHeaders))],
        Message.GetBlocks:      [0, cbor.Tag(24, cbor.dumps(Message.Block))],
        Message.Stream:         [0, cbor.Tag(24, cbor.dumps(Message.StreamBlock))],
        #0x0d:  [0, cbor.Tag(24, cbor.dumps(0x00))],
        #0x0e:  [0, cbor.Tag(24, cbor.dumps(0x00))],
        #0x25:  [0, cbor.Tag(24, cbor.dumps(0x5e))],
        #0x2b:  [0, cbor.Tag(24, cbor.dumps(0x5d))],
        #0x31:  [0, cbor.Tag(24, cbor.dumps(0x5c))],
        #0x37:  [0, cbor.Tag(24, cbor.dumps(0x62))],
        #0x3d:  [0, cbor.Tag(24, cbor.dumps(0x61))],
        #0x43:  [0, cbor.Tag(24, cbor.dumps(0x60))],
        #0x49:  [0, cbor.Tag(24, cbor.dumps(0x5f))],
        #0x53:  [0, cbor.Tag(24, cbor.dumps(0x00))],
    },
]
Example #15
0
def encode_with_crc(v):
    s = cbor.dumps(v)
    return cbor.dumps([cbor.Tag(24, s), binascii.crc32(s)])
Example #16
0
 def to_suit(self):
     for k, f in self.fields.items():
         v = getattr(self, k, None)
         if v:
             return cbor.Tag(tag=f.suit_key, value=v.to_suit())
     return None
Example #17
0
def generate_static_auth_data_for_auth_key(doc_type, name_spaces,
                                           credential_key, auth_key,
                                           issuer_key, issuer_cert):
    # First, randomize the order the digest IDs are used
    num_elems = 0
    for ns_name in name_spaces.keys():
        num_elems += len(name_spaces[ns_name])
        digest_ids = list(range(num_elems))
        random.shuffle(digest_ids)

    # Along with value_digests for the MSO, generate digest_id_mapping which is sent
    # to the mDL along with the MSO
    #
    #     DigestIdMapping = {
    #         NameSpace => [ + IssuerSignedItemBytes ]
    #     }
    #
    #     ; Defined in ISO 18013-5
    #     ;
    #     NameSpace = String
    #     DataElementIdentifier = String
    #     DigestID = uint
    #     IssuerAuth = COSE_Sign1 ; The payload is MobileSecurityObjectBytes
    #
    #     IssuerSignedItemBytes = #6.24(bstr .cbor IssuerSignedItem)
    #
    #     IssuerSignedItem = {
    #       "digestID" : uint,                           ; Digest ID for issuer data auth
    #       "random" : bstr,                             ; Random value for issuer data auth
    #       "elementIdentifier" : DataElementIdentifier, ; Data element identifier
    #       "elementValue" : DataElementValue            ; Data element value
    #     }
    #
    value_digests = {}
    digest_id_mapping = {}
    digest_id_index = 0
    for ns_name in name_spaces.keys():
        value_digests_for_ns = {}
        issuer_signed_item_for_ns = []
        for elem in name_spaces[ns_name]:
            digest_id = digest_ids[digest_id_index]
            elem_random = bytes(random.randint(0, 255) for i in range(32))
            digest_id_index += 1
            # Calculate the digest
            # TODO: send to the device the issuer signed item bytes
            encoded_issuer_signed_item = cbor.dumps(
                cbor.Tag(
                    24,
                    cbor.dumps({
                        "random": elem_random,
                        "digestID": digest_id,
                        "elementValue": elem["value"],
                        "elementIdentifier": elem["name"],
                    })))
            encoded_issuer_signed_item_value_null = cbor.dumps(
                cbor.Tag(
                    24,
                    cbor.dumps({
                        "random": elem_random,
                        "digestID": digest_id,
                        "elementValue": None,
                        "elementIdentifier": elem["name"],
                    })))
            digest = hashlib.sha256(encoded_issuer_signed_item).digest()
            value_digests_for_ns[digest_id] = digest
            value_digests[ns_name] = value_digests_for_ns
            issuer_signed_item_for_ns.append(
                encoded_issuer_signed_item_value_null)
            digest_id_mapping[ns_name] = issuer_signed_item_for_ns

    now = datetime.datetime.now(datetime.timezone.utc)
    signed_time = now
    valid_from = now
    # MSO is valid for one year
    valid_to = now + datetime.timedelta(days=365)
    validity_info = {
        "signed": cbor.Tag(6, signed_time.isoformat()),
        "validFrom": cbor.Tag(6, valid_from.isoformat()),
        "validUntil": cbor.Tag(6, valid_to.isoformat()),
        # expectedUpdate not set
    }

    device_key_info = {
        "deviceKey": to_cose_key(auth_key),
        # keyAuthorizations and keyInfo not set
    }

    mobile_security_object = {
        "version": "1",
        "digestAlgorithm": "SHA-256",
        "valueDigests": value_digests,
        "deviceKeyInfo": device_key_info,
        "docType": doc_type,
        "validityInfo": validity_info,
    }

    mobile_security_object_bytes = cbor.dumps(
        cbor.Tag(24, cbor.dumps(mobile_security_object)))
    signature_with_mso = cose_sign1_sign(issuer_key,
                                         mobile_security_object_bytes, False,
                                         issuer_cert)

    static_auth_data = {
        "digestIdMapping": digest_id_mapping,
        "issuerAuth": signature_with_mso,
    }
    encoded_static_auth_data = cbor.dumps(static_auth_data)
    return encoded_static_auth_data
Example #18
0
def setup_test_data(database):
    db = database.get_sqlite3()
    c = db.cursor()

    # Erika Mustermann
    #
    mdl_acp_cbor = cbor.dumps([{
        "id": 0,
        "userAuthenticationRequired": True,
        "timeoutMillis": 1000
    }], )
    with open("erika_portrait.jpg", "rb") as f:
        portrait = f.read()
    mdl_ns_cbor = cbor.dumps({
        "org.iso.18013.5.1": [{
            "name": "family_name",
            "value": "Mustermann",
            "accessControlProfiles": [0]
        }, {
            "name": "given_name",
            "value": "Erika",
            "accessControlProfiles": [0]
        }, {
            "name": "portrait",
            "value": portrait,
            "accessControlProfiles": [0]
        }, {
            "name": "birth_date",
            "value": cbor.Tag(6, "1971-09-01"),
            "accessControlProfiles": [0]
        }],
        "org.aamva.18013.5.1": [{
            "name": "real_id",
            "value": True,
            "accessControlProfiles": [0]
        }]
    })
    c.execute(
        "INSERT INTO persons (person_id, name, portrait) VALUES (10, 'Erika Mustermann', ?);",
        [portrait])
    # get 'now(UTC)' to create a new timestamp for 'data_timestamp'
    now = datetime.datetime.now(datetime.timezone.utc)
    data_timestamp = datetime.datetime.timestamp(now)
    c.execute(
        "INSERT INTO documents (document_id, person_id, doc_type, access_control_profiles, name_spaces, data_timestamp) "
        "VALUES (11, 10, 'org.iso.18013.5.1.mDL', ?, ?, ?);",
        (mdl_acp_cbor, mdl_ns_cbor, data_timestamp))
    c.execute(
        "INSERT INTO issued_documents (issued_document_id, document_id, provisioning_code) "
        "VALUES (12, 11, '1001');")

    # John Doe
    #
    with open("john_doe_portrait.jpg", "rb") as f:
        portrait = f.read()
    mdl_ns_cbor = cbor.dumps({
        "org.iso.18013.5.1": [{
            "name": "family_name",
            "value": "Doe",
            "accessControlProfiles": [0]
        }, {
            "name": "given_name",
            "value": "John",
            "accessControlProfiles": [0]
        }, {
            "name": "portrait",
            "value": portrait,
            "accessControlProfiles": [0]
        }],
        "org.aamva.18013.5.1": [{
            "name": "real_id",
            "value": True,
            "accessControlProfiles": [0]
        }]
    })
    c.execute(
        "INSERT INTO persons (person_id, name, portrait) VALUES (20, 'John Doe', ?);",
        [portrait])
    # get 'now(UTC)' to create a new timestamp for 'data_timestamp'
    now = datetime.datetime.now(datetime.timezone.utc)
    data_timestamp = datetime.datetime.timestamp(now)
    c.execute(
        "INSERT INTO documents (document_id, person_id, doc_type, access_control_profiles, name_spaces, data_timestamp) "
        "VALUES (21, 20, 'org.iso.18013.5.1.mDL', ?, ?, ?);",
        (mdl_acp_cbor, mdl_ns_cbor, data_timestamp))
    c.execute(
        "INSERT INTO issued_documents (issued_document_id, document_id, provisioning_code) "
        "VALUES (22, 21, '2001');")

    db.commit()