Example #1
0
    def __init__(self, signed_se, verification_cert_raw):
        verification_cert = x509.load_pem_x509_certificate(
            data=verification_cert_raw,
            backend=default_backend()
        )

        self.signed_se = signed_se
        self.ski_ext = verification_cert.extensions.get_extension_for_class(
            extclass=x509.SubjectKeyIdentifier
        )
    
        self.verification_cert_kid_b64 = base64url_encode(
            self.ski_ext.value.digest
        ).decode('ascii')

        self.verification_public_key_pem = verification_cert.public_key().public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        ).decode('ascii')

        self.verification_cert_x5t_s256_b64 = base64url_encode(
            verification_cert.fingerprint(hashes.SHA256())
        ).decode('ascii')
        self.certificate_chain = ''
        self.run()
Example #2
0
    def __init__(self, wallet, **kwargs):
        self.jwk_data = wallet.jwk_data
        self.jwk = jwk.construct(self.jwk_data, algorithm="RS256")

        self.id = kwargs.get('id', '')
        self.last_tx = wallet.get_last_transaction_id()
        self.owner = self.jwk_data.get('n')
        self.tags = []
        self.quantity = kwargs.get('quantity', '0')

        data = kwargs.get('data', '')
        if type(data) is bytes:
            self.data = base64url_encode(data)
        else:
            self.data = base64url_encode(data.encode('ascii'))
        self.target = kwargs.get('target', '')
        self.to = kwargs.get('to', '')

        self.api_url = "https://arweave.net"

        reward = kwargs.get('reward', None)
        if reward != None:
            self.reward = reward
        else:
            self.reward = self.get_reward(self.data)

        self.signature = ''
        self.status = None
    def __init__(self, wallet, **kwargs):
        self.jwk_data = wallet.jwk_data
        self.jwk = jwk.construct(self.jwk_data, algorithm="RS256")
        self.wallet = wallet

        self.id = kwargs.get('id', '')
        self.last_tx = wallet.get_last_transaction_id()
        self.owner = self.jwk_data.get('n')
        self.tags = []
        self.format = kwargs.get('format', 2)

        self.api_url = API_URL
        self.chunks = None

        data = kwargs.get('data', '')
        self.data_size = len(data)

        if type(data) is bytes:
            self.data = base64url_encode(data)
        else:
            self.data = base64url_encode(data.encode('utf-8'))

        if self.data is None:
            self.data = ''

        self.file_handler = kwargs.get('file_handler', None)
        if self.file_handler:
            self.uses_uploader = True
            self.data_size = os.stat(kwargs['file_path']).st_size
        else:
            self.uses_uploader = False

        if kwargs.get('transaction'):
            self.from_serialized_transaction(kwargs.get('transaction'))
        else:
            self.data_root = ""

            self.data_tree = []

            self.target = kwargs.get('target', '')
            self.to = kwargs.get('to', '')

            if self.target == '' and self.to != '':
                self.target = self.to

            self.quantity = kwargs.get('quantity', '0')
            if float(self.quantity) > 0:
                if self.target == '':
                    raise ArweaveTransactionException(
                        "Unable to send {} AR without specifying a target address".format(self.quantity))

                # convert to winston
                self.quantity = ar_to_winston(float(self.quantity))

            reward = kwargs.get('reward', None)
            if reward is not None:
                self.reward = reward

            self.signature = ''
            self.status = None
    def sign(self, wallet):
        data_to_sign = self.get_signature_data()

        raw_signature = wallet.sign(data_to_sign)

        self.signature = base64url_encode(raw_signature)

        self.id = base64url_encode(hashlib.sha256(raw_signature).digest())
Example #5
0
def create_tag(name, value, v2):
    if v2:
        b64name = name
        b64value = value
    else:
        b64name = base64url_encode(name.encode('ascii')).decode()
        b64value = base64url_encode(value.encode('ascii')).decode()

    return {"name": b64name, "value": b64value}
Example #6
0
 def set_keys(self):
     for ec_priv_key in [0, 1, 2, 3, 4]:
         public_key = bytearray()
         assert atcab_get_pubkey(
             ec_priv_key,
             public_key) == Status.ATCA_SUCCESS, 'Reading Pub key failed'
         x = utils.base64url_encode(public_key[0:32]).decode('ascii')
         y = utils.base64url_encode(public_key[32:64]).decode('ascii')
         self.set_publicJWK(str(ec_priv_key), 'EC', 'P-256', x, y, x5c=None)
Example #7
0
    def generatePkce(self, challengeMethod):
        if challengeMethod != 'plain' and challengeMethod != 'S256':
            raise ParamError('challengeMethod')

        try:
            codeVerifier = self.__generateVerifier(128)
            logger.debug('codeVerifier=' + codeVerifier)
            logger.debug('type(codeVerifier)=' + str(type(codeVerifier)))
            if challengeMethod == 'plain':
                codeChallenge = codeVerifier
            elif challengeMethod == 'S256':
                try:  # Python3
                    codeVerifier_bytes = codeVerifier.encode()
                    logger.debug('type(hashlib.sha256(codeVerifier_bytes)=' +
                                 str(type(hashlib.sha256(codeVerifier_bytes))))
                    logger.debug(
                        'hashlib.sha256(codeVerifier_bytes).digest()=' +
                        str(hashlib.sha256(codeVerifier_bytes).digest()))
                    logger.debug(
                        'type(hashlib.sha256(codeVerifier_bytes).digest()=' +
                        str(type(hashlib.sha256(codeVerifier_bytes).digest())))
                    logger.debug(
                        'base64url_encode(hashlib.sha256(codeVerifier_bytes).digest())='
                        + str(
                            base64url_encode(
                                hashlib.sha256(codeVerifier_bytes).digest())))
                    logger.debug(
                        'type(base64url_encode(hashlib.sha256(codeVerifier_bytes).digest())='
                        + str(
                            type(
                                base64url_encode(
                                    hashlib.sha256(
                                        codeVerifier_bytes).digest()))))
                    codeChallenge = base64url_encode(
                        hashlib.sha256(codeVerifier_bytes).digest()).decode(
                            'utf-8')
                    logger.debug('codeChallenge=' + codeChallenge)
                    logger.debug('type(codeChallenge)=' +
                                 str(type(codeChallenge)))
                except:  # Python2
                    codeChallenge = base64url_encode(
                        hashlib.sha256(codeVerifier).digest())
            else:
                raise ParamError('challengeMethod')
            self.session['challengeMethod'] = challengeMethod
            self.session['codeVerifier'] = codeVerifier
            self.session['codeChallenge'] = codeChallenge
        except TypeError as exp:
            logger.error('[OIDCTokenStore.generatePkce] [TypeError] ' +
                         str(exp))
            raise
        except Exception as exp:
            logger.error('[OIDCTokenStore.generatePkce] ' + str(exp))
            raise
    def sign(self):
        data_to_sign = self.get_signature_data()

        raw_signature = self.wallet.sign(data_to_sign)

        self.signature = base64url_encode(raw_signature)

        self.id = base64url_encode(hashlib.sha256(raw_signature).digest())

        if type(self.id) == bytes:
            self.id = self.id.decode()
Example #9
0
def _encode_claims(claims):
    json_payload = json.dumps(
        claims,
        separators=(',', ':'),
    ).encode('utf-8')

    return base64url_encode(json_payload)
Example #10
0
 def to_dict(self):
     print("boom!")
     return {
         "dataHash": base64url_encode(self.data_hash).decode(),
         "maxByteRange": self.max_byte_range,
         "minByteRange": self.min_byte_range
     }
Example #11
0
def _encode_claims(claims):
    json_payload = json.dumps(
        claims,
        separators=(',', ':'),
    ).encode('utf-8')

    return base64url_encode(json_payload)
    def get_chunk(self, idx):
        if self.chunks is None:
            raise ArweaveTransactionException("Chunks have not been prepared")

        proof = self.chunks.get('proofs')[idx]
        chunk = self.chunks.get('chunks')[idx]

        self.file_handler.seek(chunk.min_byte_range)

        chunk_data = self.file_handler.read(chunk.data_size)

        return {
            "data_root": self.data_root.decode(),
            "data_size": str(self.data_size),
            "data_path": base64url_encode(proof.proof),
            "offset": str(proof.offset),
            "chunk": base64url_encode(chunk_data)
        }
    def prepare_chunks(self):
        if not self.chunks:
            self.chunks = generate_transaction_chunks(self.file_handler)
            self.data_root = base64url_encode(self.chunks.get('data_root'))

        if not self.chunks:
            self.chunks = {"chunks": [], "data_root": b'', "proof": []}

            self.data_root = ''
Example #14
0
    def __init__(self, signed_se, verification_cert):
        self.signed_se = signed_se
        self.ski_ext = verification_cert.extensions.get_extension_for_class(
            extclass=x509.SubjectKeyIdentifier)

        self.verification_cert_kid_b64 = base64url_encode(
            self.ski_ext.value.digest).decode("ascii")

        self.verification_public_key_pem = (
            verification_cert.public_key().public_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PublicFormat.SubjectPublicKeyInfo,
            ).decode("ascii"))

        self.verification_cert_x5t_s256_b64 = base64url_encode(
            verification_cert.fingerprint(hashes.SHA256())).decode("ascii")
        self.certificate_chain = ""
        self.run()
Example #15
0
 def generate_at_hash(access_token):
     """
     Get hash for JWT access token.
     """
     hash = hashlib.sha256()
     hash.update(access_token.encode())
     digest = hash.digest()
     digest_truncated = digest[:(int(len(digest) / 2))]
     at_hash = base64url_encode(digest_truncated).decode()
     return at_hash
Example #16
0
def _encode_payload(payload):
    if isinstance(payload, Mapping):
        try:
            payload = json.dumps(
                payload,
                separators=(',', ':'),
            )
        except ValueError:
            pass

    return base64url_encode(six.ensure_binary(payload))
Example #17
0
def _encode_payload(payload):
    if isinstance(payload, Mapping):
        try:
            payload = json.dumps(
                payload,
                separators=(',', ':'),
            ).encode('utf-8')
        except ValueError:
            pass

    return base64url_encode(payload)
Example #18
0
def _encode_payload(payload):
    if isinstance(payload, Mapping):
        try:
            payload = json.dumps(
                payload,
                separators=(',', ':'),
            ).encode('utf-8')
        except ValueError:
            pass

    return base64url_encode(payload)
Example #19
0
def hash(data):
    if type(data) == list:
        byte_str = b''
        for line in data:
            byte_str += line

        data = byte_str

    digest = hashlib.sha256(data).digest()
    b64_str = base64url_encode(digest)
    return digest
    def get_signature_data(self):
        self.reward = self.get_reward(
            self.data_size,
            target_address=self.target if len(self.target) > 0 else None)

        if int(self.data_size
               ) > 0 and self.data_root == "" and not self.uses_uploader:
            if type(self.data) == str:
                root_hash = compute_root_hash(io.StringIO(self.data))

            if type(self.data) == bytes:
                root_hash = compute_root_hash(io.BytesIO(self.data))

            self.data_root = base64url_encode(root_hash)

        if self.format == 1:
            tag_str = ""

            for tag in self.tags:
                name, value = decode_tag(tag)
                tag_str += "{}{}".format(name.decode(), value.decode())

            owner = base64url_decode(self.jwk_data['n'].encode())
            target = base64url_decode(self.target)
            data = base64url_decode(self.data)
            quantity = self.quantity.encode()
            reward = self.reward.encode()
            last_tx = base64url_decode(self.last_tx.encode())

            signature_data = owner + target + data + quantity + reward + last_tx + tag_str.encode(
            )

        if self.format == 2:
            if self.uses_uploader:
                self.prepare_chunks()

            tag_list = [[tag['name'].encode(), tag['value'].encode()]
                        for tag in self.tags]

            signature_data_list = [
                "2".encode(),
                base64url_decode(self.jwk_data['n'].encode()),
                base64url_decode(self.target.encode()),
                str(self.quantity).encode(),
                self.reward.encode(),
                base64url_decode(self.last_tx.encode()), tag_list,
                str(self.data_size).encode(),
                base64url_decode(self.data_root)
            ]

            signature_data = deep_hash(signature_data_list)

        return signature_data
Example #21
0
def _encode_header(algorithm, additional_headers=None):
    header = {"typ": "JWT", "alg": algorithm}

    if additional_headers:
        header.update(additional_headers)

    json_header = json.dumps(
        header,
        separators=(',', ':'),
    ).encode('utf-8')

    return base64url_encode(json_header)
Example #22
0
def _sign_header_and_claims(encoded_header, encoded_claims, algorithm, key_data):
    signing_input = b'.'.join([encoded_header, encoded_claims])
    try:
        key = jwk.construct(key_data, algorithm)
        signature = key.sign(signing_input)
    except Exception as e:
        raise JWSError(e)

    encoded_signature = base64url_encode(signature)

    encoded_string = b'.'.join([encoded_header, encoded_claims, encoded_signature])

    return encoded_string.decode('utf-8')
Example #23
0
def _sign_header_and_claims(encoded_header, encoded_claims, algorithm, key_data):
    signing_input = b'.'.join([encoded_header, encoded_claims])
    try:
        key = jwk.construct(key_data, algorithm)
        signature = key.sign(signing_input)
    except Exception as e:
        raise JWSError(e)

    encoded_signature = base64url_encode(signature)

    encoded_string = b'.'.join([encoded_header, encoded_claims, encoded_signature])

    return encoded_string.decode('utf-8')
Example #24
0
def _encode_header(algorithm, additional_headers=None):
    header = {"typ": "JWT", "alg": algorithm}

    if additional_headers:
        header.update(additional_headers)

    json_header = json.dumps(
        header,
        separators=(",", ":"),
        sort_keys=True,
    ).encode("utf-8")

    return base64url_encode(json_header)
Example #25
0
def _sign_header_and_claims(encoded_header, encoded_claims, algorithm, key):
    signing_input = b".".join([encoded_header, encoded_claims])
    try:
        if not isinstance(key, Key):
            key = jwk.construct(key, algorithm)
        signature = key.sign(signing_input)
    except Exception as e:
        raise JWSError(e)

    encoded_signature = base64url_encode(signature)

    encoded_string = b".".join([encoded_header, encoded_claims, encoded_signature])

    return encoded_string.decode("utf-8")
Example #26
0
def _sign_header_and_claims(encoded_header, encoded_claims, algorithm, key):
    signing_input = b'.'.join([encoded_header, encoded_claims])
    try:
        alg_obj = get_algorithm_object(algorithm)
        key = alg_obj.prepare_key(key)
        signature = alg_obj.sign(signing_input, key)
    except Exception as e:
        raise JWSError(e)

    encoded_signature = base64url_encode(signature)

    encoded_string = b'.'.join([encoded_header, encoded_claims, encoded_signature])

    return encoded_string.decode('utf-8')
Example #27
0
def _encode_header(algorithm, additional_headers=None):
    header = {
        "typ": "JWT",
        "alg": algorithm
    }

    if additional_headers:
        header.update(additional_headers)

    json_header = json.dumps(
        header,
        separators=(',', ':'),
    ).encode('utf-8')

    return base64url_encode(json_header)
 def test_1_7_4_generatePkce_s256_normal(self):
     "Generating Plain CodeChallenge from OIDCTokenStore Model."
     tokenstore = OIDCTokenStore(self.opId, self.session)
     cc = tokenstore.generatePkce('S256')
     self.assertEquals(
         self.session[settings.OIDC_TOKENSTORE_COOKIENAME +
                      self.opId]['challengeMethod'], 'S256')
     try:
         codeChallenge = base64url_encode(
             hashlib.sha256(
                 self.session[settings.OIDC_TOKENSTORE_COOKIENAME +
                              self.opId]
                 ['codeVerifier'].encode()).digest()).decode('utf-8')
         self.assertEquals(
             self.session[settings.OIDC_TOKENSTORE_COOKIENAME +
                          self.opId]['codeChallenge'], codeChallenge)
     except:
         self.assertEquals(
             self.session[settings.OIDC_TOKENSTORE_COOKIENAME +
                          self.opId]['codeChallenge'],
             base64url_encode(
                 hashlib.sha256(
                     self.session[settings.OIDC_TOKENSTORE_COOKIENAME +
                                  self.opId]['codeVerifier']).digest()))
Example #29
0
def _sign_header_and_claims(encoded_header, encoded_claims, algorithm, key):
    signing_input = b'.'.join([encoded_header, encoded_claims])
    try:
        alg_obj = get_algorithm_object(algorithm)
        key = alg_obj.prepare_key(key)
        signature = alg_obj.sign(signing_input, key)
    except Exception as e:
        raise JWSError(e)

    encoded_signature = base64url_encode(signature)

    encoded_string = b'.'.join(
        [encoded_header, encoded_claims, encoded_signature])

    return encoded_string.decode('utf-8')
Example #30
0
def _encode_header(algorithm, additional_headers=None):
    header = {
        "typ": "JWT",
        "alg": algorithm
    }

    if additional_headers:
        header.update(additional_headers)

    json_header = six.ensure_binary(json.dumps(
        header,
        separators=(',', ':'),
        sort_keys=True,
    ))

    return base64url_encode(json_header)
Example #31
0
async def _verify_signature(app, jws, payload):
    jws_header_b64, _, signature_b64 = jws.split('.')
    signature = base64url_decode(signature_b64.encode())
    header_str = base64url_decode(jws_header_b64.encode())
    header = json.loads(header_str)

    if header.get('jku') != app.config.expected_jwks_uri:
        return False
    response = await app.aiohttp_session.get(app.config.expected_jwks_uri)
    jwks = await response.json()
    # Get the first key with ID matching the header's
    raw_key = next(k for k in jwks['keys'] if k.get('kid') == header['kid'])
    key = jwk.construct(raw_key)
    payload_b64 = base64url_encode(payload).decode()
    secured_input = f'{jws_header_b64}.{payload_b64}'

    return key.verify(secured_input.encode(), signature)
def generate_manifest(signer_certificate,
                      device_certificate,
                      log_key_path=LOGGING_KEY,
                      log_cert_path=LOGGING_CERT):
    device_entry = {
        'version': 1,
        'model': 'ATECC608A',
        'partNumber': 'ATECC608A-TFLXTLS',
        'manufacturer': {
            'organizationName': 'Microchip Technology Inc',
            'organizationalUnitName': 'Secure Products Group'
        },
        'provisioner': {
            'organizationName': 'Microchip Technology Inc',
            'organizationalUnitName': 'Secure Products Group'
        },
        'distributor': {
            'organizationName': 'Microchip Technology Inc',
            'organizationalUnitName': 'Microchip Direct'
        }
    }

    device_entry[
        'provisioningTimestamp'] = device_certificate.not_valid_before.strftime(
            '%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'

    serial_number = bytearray(9)
    assert atcab_read_serial_number(serial_number) == Status.ATCA_SUCCESS
    device_entry['uniqueId'] = serial_number.hex()

    device_entry['publicKeySet'] = {
        'keys': [{
            'kid':
            '0',
            'kty':
            'EC',
            'crv':
            'P-256',
            'x':
            None,
            'y':
            None,
            'x5c': [
                base64.b64encode(
                    device_certificate.public_bytes(
                        encoding=serialization.Encoding.DER)).decode('ascii'),
                base64.b64encode(
                    signer_certificate.public_bytes(
                        encoding=serialization.Encoding.DER)).decode('ascii')
            ]
        }, {
            'kid': '1',
            'kty': 'EC',
            'crv': 'P-256',
            'x': None,
            'y': None,
        }, {
            'kid': '2',
            'kty': 'EC',
            'crv': 'P-256',
            'x': None,
            'y': None,
        }, {
            'kid': '3',
            'kty': 'EC',
            'crv': 'P-256',
            'x': None,
            'y': None,
        }, {
            'kid': '4',
            'kty': 'EC',
            'crv': 'P-256',
            'x': None,
            'y': None,
        }]
    }

    print('Generating manifest file...', end='')
    for key in device_entry['publicKeySet']['keys']:
        public_key = bytearray(64)
        #print('reading slot {} public key'.format(key['kid']))
        assert atcab_get_pubkey(int(key['kid']),
                                public_key) == Status.ATCA_SUCCESS
        key['x'] = utils.base64url_encode(public_key[0:32]).decode('ascii')
        key['y'] = utils.base64url_encode(public_key[32:64]).decode('ascii')

    # If a logging key and certificate was provided create a manifest file
    log_key, log_cert = certs_handler.load_key_and_cert(
        log_key_path, log_cert_path)

    # Generate the key and certificate ids for JWS
    log_key_id = certs_handler.jws_b64encode(
        log_cert.extensions.get_extension_for_class(
            x509.SubjectKeyIdentifier).value.digest)
    log_cert_id = certs_handler.jws_b64encode(
        log_cert.fingerprint(hashes.SHA256()))

    # Precompute the JWT header
    jws_header = {
        'typ': 'JWT',
        'alg': 'ES256',
        'kid': log_key_id,
        'x5t#S256': log_cert_id
    }
    jws_header = certs_handler.jws_b64encode(
        json.dumps(jws_header).encode('ascii'))

    manifest = json.dumps(
        [certs_handler.create_signed_entry(device_entry, log_key, jws_header)],
        indent=2).encode('ascii')

    filename = common_helper.make_valid_filename(
        device_entry['uniqueId'].upper()) + '_manifest' + '.json'
    with open(filename, 'wb') as f:
        f.write(manifest)
    print('OK (saved to {})'.format(filename))
Example #33
0
 def to_dict(self):
     return {
         'alg': self._algorithm,
         'kty': 'oct',
         'k': base64url_encode(self.prepared_key),
     }
Example #34
0
def generate_manifest_file(esp, args, init_mfg):

    retval = init_mfg.exec_cmd(esp._port, "print-chip-info")
    serial.esp_cmd_check_ok(retval, "print-chip-info")
    # find index fo SN in string
    index = retval[1]['Return'].find("Serial Number:")
    index += len("Serial Number:")
    serial_number_hex = retval[1]['Return'][index:]
    serial_number_hex = serial_number_hex.strip()
    serial_number_hex = serial_number_hex.replace(' ','')
    print('Serial Number:')
    print(serial_number_hex.upper())
    if args.print_atecc608a_type is True:
       # only print chip info and exit.
        exit(0)

    print("Generating Manifest")
    certs = []

    retval = init_mfg.exec_cmd(esp._port, "get-tngtls-root-cert")
    serial.esp_cmd_check_ok(retval, "get-tngtls-root-cert")

    index = retval[1]['Return'].find("Root Cert Len:")
    index += len("Root Cert Len:")
    root_cert_size = retval[1]['Return'][index:index + 3]
    root_cert_size = int(root_cert_size)
    root_cert_der = bytearray(root_cert_size)
    index = retval[1]['Return'].find("Certificate:")
    index += len("Certificate:")
    root_cert_hex = retval[1]['Return'][index + 1:]
    root_cert_hex = root_cert_hex.strip()
    root_cert_der = bytearray.fromhex(root_cert_hex)

    root_cert = x509.load_der_x509_certificate(root_cert_der, default_backend())
    certs.insert(0, root_cert)

    print(get_common_name(root_cert.subject))
    print(root_cert.public_bytes(encoding=Encoding.PEM).decode('utf-8'))

    print('TNG Root Public Key:')

    print(root_cert.public_key().public_bytes(
        format=PublicFormat.SubjectPublicKeyInfo,
        encoding=Encoding.PEM
    ).decode('utf-8'))

    retval = init_mfg.exec_cmd(esp._port, "get-tngtls-signer-cert")
    serial.esp_cmd_check_ok(retval, "get-tngtls-signer-cert")

    index = retval[1]['Return'].find("Signer Cert Len:")
    index += len("Signer Cert Len:")
    signer_cert_size = retval[1]['Return'][index:index + 3]
    signer_cert_size = int(signer_cert_size)
    signer_cert_der = bytearray(signer_cert_size)
    index = retval[1]['Return'].find("Certificate:")
    index += len("Certificate:")
    signer_cert_hex = retval[1]['Return'][index:]
    signer_cert_hex = signer_cert_hex.strip()
    signer_cert_der = bytearray.fromhex(signer_cert_hex)

    print('TNG Signer Certificate:')
    signer_cert = x509.load_der_x509_certificate(signer_cert_der, default_backend())
    certs.insert(0, signer_cert)

    print(get_common_name(signer_cert.subject))
    print(signer_cert.public_bytes(encoding=Encoding.PEM).decode('utf-8'))

    print('TNG Signer Public Key:')

    print(signer_cert.public_key().public_bytes(
        format=PublicFormat.SubjectPublicKeyInfo,
        encoding=Encoding.PEM
    ).decode('utf-8'))

    # Note that this is a simple cryptographic validation and does not check
    # any of the actual certificate data (validity dates, extensions, names,
    # etc...)
    print('Validate Signer Certificate:')
    root_cert.public_key().verify(
        signature=signer_cert.signature,
        data=signer_cert.tbs_certificate_bytes,
        signature_algorithm=ec.ECDSA(signer_cert.signature_hash_algorithm)
    )
    print('OK\n')

    print('TNG Device Certificate:')

    retval = init_mfg.exec_cmd(esp._port, "get-tngtls-device-cert")
    serial.esp_cmd_check_ok(retval, "get-tngtls-device-cert")

    index = retval[1]['Return'].find("Device Cert Len:")
    index += len("Device Cert Len:")
    device_cert_size = retval[1]['Return'][index:index + 3]
    device_cert_size = int(device_cert_size)
    device_cert_der = bytearray(device_cert_size)
    index = retval[1]['Return'].find("Certificate:")
    index += len("Certificate:")

    device_cert_hex = retval[1]['Return'][index:]
    device_cert_hex = device_cert_hex.strip()
    device_cert_der = bytearray.fromhex(device_cert_hex)
    device_cert = x509.load_der_x509_certificate(device_cert_der, default_backend())
    certs.insert(0, device_cert)

    print(get_common_name(device_cert.subject))
    device_cert_pem = device_cert.public_bytes(encoding=Encoding.PEM).decode('utf-8')
    print(device_cert_pem)
    print("Saving device cert to output_files")
    
    with open(os.path.join(args.basepath, "device_cert.pem"), "w+") as dev_cert_file:
        dev_cert_file.write(device_cert_pem)
    print('TNG Device Public Key:')
    # Note that we could, of course, pull this from the device certificate above.
    # However, this demonstrates the tng_atcacert_device_public_key() function.

    print(device_cert.public_key().public_bytes(
        format=PublicFormat.SubjectPublicKeyInfo,
        encoding=Encoding.PEM
    ).decode('utf-8'))

    print('Validate Device Certificate:')
    signer_cert.public_key().verify(
        signature=device_cert.signature,
        data=device_cert.tbs_certificate_bytes,
        signature_algorithm=ec.ECDSA(device_cert.signature_hash_algorithm)
    )
    print('OK\n')

    device_entry = {
        'version': 1,
        'model': 'ATECC608A',
        'partNumber': 'ATECC608A-TNGTLS',
        'manufacturer': {
            'organizationName': 'Microchip Technology Inc',
            'organizationalUnitName': 'Secure Products Group'
        },
        'provisioner': {
            'organizationName': 'Microchip Technology Inc',
            'organizationalUnitName': 'Secure Products Group'
        },
        'distributor': {
            'organizationName': 'Microchip Technology Inc',
            'organizationalUnitName': 'Microchip Direct'
        }
    }

    device_entry['provisioningTimestamp'] = device_cert.not_valid_before.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'

    print(serial_number_hex)
    device_entry['uniqueId'] = serial_number_hex

    device_entry['publicKeySet'] = {
        'keys': [
            {
                'kid': '0',
                'kty': 'EC',
                'crv': 'P-256',
                'x': None,
                'y': None,
                'x5c': [
                    base64.b64encode(device_cert_der).decode('ascii'),
                    base64.b64encode(signer_cert_der).decode('ascii')
                ]
            },
            {'kid': '1', 'kty': 'EC', 'crv': 'P-256', 'x': None, 'y': None},
            {'kid': '2', 'kty': 'EC', 'crv': 'P-256', 'x': None, 'y': None},
            {'kid': '3', 'kty': 'EC', 'crv': 'P-256', 'x': None, 'y': None},
            {'kid': '4', 'kty': 'EC', 'crv': 'P-256', 'x': None, 'y': None}
        ]
    }

    for key in device_entry['publicKeySet']['keys']:
        public_key = bytearray(64)
        print('reading slot {} public key'.format(key['kid']))
        retval = init_mfg.exec_cmd(esp._port, "generate-pubkey {}".format(key['kid']))
        serial.esp_cmd_check_ok(retval, "pub-key-gen")
        index = retval[1]['Return'].find("Public Key:")
        index += len("Public Key:")
        public_key_hex = retval[1]['Return'][index:]
        public_key_hex = public_key_hex.strip()
        public_key = bytearray.fromhex(public_key_hex)
        key['x'] = utils.base64url_encode(public_key[0:32]).decode('ascii')
        key['y'] = utils.base64url_encode(public_key[32:64]).decode('ascii')

    # If a logging key and certificate was provided create a manifest file
    log_key = cert_sign.load_privatekey(args.signer_privkey)
    log_cert = cert_sign.load_certificate(args.signer_cert)
    # Generate the key and certificate ids for JWS
    log_key_id = jws_b64encode(log_cert.extensions.get_extension_for_class(x509.SubjectKeyIdentifier).value.digest)
    log_cert_id = jws_b64encode(log_cert.fingerprint(hashes.SHA256()))

    # Precompute the JWT header
    jws_header = {'typ': 'JWT', 'alg': 'ES256', 'kid': log_key_id, 'x5t#S256': log_cert_id}
    jws_header = jws_b64encode(json.dumps(jws_header).encode('ascii'))

    manifest = json.dumps([create_signed_entry(device_entry, log_key, jws_header)], indent=2).encode('ascii')

    filename = make_valid_filename(device_entry['uniqueId']) + '_manifest' + '.json'
    os.getcwd()
    with open(os.path.join(args.basepath, filename), 'wb') as f:
        f.write(manifest)
    print('Created: ' + filename)
Example #35
0
    def verifySig(self,
                  issuer=None,
                  clientId=None,
                  clientSecret=None,
                  accessToken=None,
                  sigAlgSupported=[],
                  JWKSet=[]):
        if not issuer or issuer is None:
            raise ParamError('issuer')
        if not clientId or clientId is None:
            raise ParamError('clientId')
        if not clientSecret or clientSecret is None:
            raise ParamError('clientSecret')
        #if not sigAlgSupported or sigAlgSupported is None:
        #	raise ParamError('sigAlgSupported')

        c = {}

        try:
            if 'id_token' not in self.session.keys(
            ) or 'id_token_decoded' not in self.session.keys():
                return c
            if 'id_token_decoded' in self.session.keys():
                id_token_decoded = json.loads(self.session['id_token_decoded'])
            if 'id_token' in self.session.keys():
                id_token = self.session['id_token']
        except Exception as exp:
            logger.error('[OIDCTokenStore.verifySig] id_token Load Error : ' +
                         str(exp))
            raise

        try:
            c['issMatching'] = None
            if 'iss' in id_token_decoded.keys():
                if id_token_decoded['iss'] == issuer:
                    c['issMatching'] = True
                else:
                    c['issMatching'] = False
        except Exception as exp:
            logger.error('[OIDCTokenStore.verifySig] iss Matching Error : ' +
                         str(exp))
            raise
        try:
            c['audMatching'] = None
            if 'aud' in id_token_decoded.keys():
                if clientId in id_token_decoded['aud']:
                    c['audMatching'] = True
                else:
                    c['audMatching'] = False
        except Exception as exp:
            logger.error('[OIDCTokenStore.verifySig] aud Matching Error : ' +
                         str(exp))
            raise
        try:
            c['azpMatching'] = None
            if 'azp' in id_token_decoded.keys():
                if clientId in id_token_decoded['azp']:
                    c['azpMatching'] = True
                else:
                    c['azpMatching'] = False
        except Exception as exp:
            logger.error('[OIDCTokenStore.verifySig] azp Matching Error : ' +
                         str(exp))
            raise
        try:
            c['expIntegrity'] = None
            if 'exp' in id_token_decoded.keys():
                if int(time.mktime(datetime.now().timetuple())) < int(
                        id_token_decoded['exp']):
                    c['expIntegrity'] = True
                else:
                    c['expIntegrity'] = False
        except Exception as exp:
            logger.error('[OIDCTokenStore.verifySig] exp Integrity Error : ' +
                         str(exp))
            raise
        try:
            c['nbfIntegrity'] = None
            if 'nbf' in id_token_decoded.keys():
                if int(time.mktime(datetime.now().timetuple())) >= int(
                        id_token_decoded['nbf']):
                    c['nbfIntegrity'] = True
                else:
                    c['nbfIntegrity'] = False
        except Exception as exp:
            logger.error('[OIDCTokenStore.verifySig] nbf Integrity Error : ' +
                         str(exp))
            raise
        try:
            c['iatIntegrity'] = None
            if 'iat' in id_token_decoded.keys():
                if (int(time.mktime(datetime.now().timetuple())) -
                        self.leeway) < int(id_token_decoded['iat']):
                    c['iatIntegrity'] = True
                else:
                    c['iatIntegrity'] = False
        except Exception as exp:
            logger.error('[OIDCTokenStore.verifySig] iat Integrity Error : ' +
                         str(exp))
            raise

        try:
            c['sigAlg'] = None
            c['sigType'] = None
            c['sigVerify'] = None
            idTokenHeaders, idTokenBody, idTokenSig = id_token.split('.')
            idTokenHeaders_padding = idTokenHeaders.replace('-', '+').replace(
                '_', '/') + ('=' * (len(idTokenHeaders) % 4))
            idTokenHeaders_decoded = json.loads(
                base64.b64decode(idTokenHeaders_padding))
            idTokenBody_padding = idTokenBody.replace('-', '+').replace(
                '_', '/') + ('=' * (len(idTokenBody) % 4))
            idTokenBody_b64decoded = base64.b64decode(idTokenBody_padding)
            if 'alg' in idTokenHeaders_decoded.keys():
                if (idTokenHeaders_decoded['alg'] in keyMap['hmacType'].keys()
                        and idTokenHeaders_decoded['alg']
                        in sigAlgSupported) or JWKSet == "":
                    c['sigType'] = 'Symmetric'
                    c['sigAlg'] = idTokenHeaders_decoded['alg']
                    dmod = keyMap['hmacType'][idTokenHeaders_decoded['alg']]
                    sig_digest = hmac.new(
                        clientSecret.encode(),
                        '.'.join([idTokenHeaders, idTokenBody]).encode(),
                        digestmod=dmod).digest()
                    sig = base64.b64encode(sig_digest).decode('utf-8').replace(
                        '+', '-').replace('/', '_').replace('=', '')
                    logger.debug('sig       =' + sig)
                    logger.debug('idTokenSig=' + idTokenSig)
                    c['sigVerify'] = (sig == idTokenSig)

                elif idTokenHeaders_decoded['alg'] in [
                        'RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512'
                ] and idTokenHeaders_decoded['alg'] in sigAlgSupported:
                    c['sigType'] = 'Asymmetric'
                    c['sigAlg'] = idTokenHeaders_decoded['alg']
                    try:  # Python3
                        jwkstr = json.dumps(JWKSet).encode()
                    except:  # Python2
                        jwkstr = json.dumps(JWKSet).decode('utf-8')
                    logger.debug('type(jwkstr)=' + str(type(jwkstr)))
                    result = jws.verify(
                        id_token,
                        jwkstr,
                        algorithms=idTokenHeaders_decoded['alg'])
                    logger.debug('verify result=' + str(result))
                    if json.dumps(json.loads(result)) == json.dumps(
                            json.loads(idTokenBody_b64decoded)):
                        c['sigVerify'] = True
                        logger.debug('verify is True')
                    else:
                        c['sigVerify'] = False
                        logger.debug('verify is False')

                elif idTokenHeaders_decoded['alg'] == 'none':
                    c['sigType'] = 'Unsecured'
                    c['sigAlg'] = idTokenHeaders_decoded['alg']
                else:
                    c['sigType'] = 'Unknown'
                    c['sigAlg'] = idTokenHeaders_decoded['alg']
        except Exception as exp:
            logger.error('[OIDCTokenStore.verifySig] sig Validation Error : ' +
                         str(exp))
            raise

        try:
            c['sigATHash'] = None
            logger.debug('accessToken=' + str(accessToken))
            logger.debug('type(accessToken)=' + str(type(accessToken)))
            if accessToken is not None:
                logger.debug('1')
                if 'at_hash' in id_token_decoded.keys():
                    try:  # Python3
                        accessToken_bytes = accessToken.encode()
                        logger.debug('accessToken_bytes=' +
                                     str(accessToken_bytes))
                        logger.debug('type(accessToken_bytes)=' +
                                     str(type(accessToken_bytes)))
                        digest = hashlib.sha256(accessToken_bytes).digest()
                        computed_hash = base64url_encode(
                            digest[:len(digest) // 2]).decode('utf-8').replace(
                                '=', '')
                        logger.debug('digest=' + str(digest))
                        logger.debug('type(digest)=' + str(type(digest)))
                        logger.debug(
                            'base64url_encode(digest[:len(digest)//2]).decode("utf-8").replace("=","")='
                            +
                            base64url_encode(digest[:len(digest) // 2]).decode(
                                'utf-8').replace('=', ''))
                        logger.debug(
                            'type(base64url_encode(digest[:len(digest)//2]).decode("utf-8").replace("=",""))='
                            + str(
                                type(
                                    base64url_encode(digest[:len(digest) // 2])
                                    .decode('utf-8').replace('=', ''))))
                        logger.debug('id_token_decoded["at_hash"]=' +
                                     id_token_decoded['at_hash'])
                    except:  # Python2
                        digest = hashlib.sha256(accessToken).digest()
                        computed_hash = base64url_encode(
                            digest[:len(digest) // 2]).replace('=', '')

                    if id_token_decoded['at_hash'] == computed_hash:
                        c['sigATHash'] = True
                    else:
                        c['sigATHash'] = False
        except Exception as exp:
            logger.error(
                '[OIDCTokenStore.verifySig] at_hash Validation Error : ' +
                str(exp))
            raise

        return c