def test_a_1_1c(): hmac = intarr2bin(HMAC_KEY) signer = SIGNER_ALGS["HS256"] header = b'{"typ":"JWT",\r\n "alg":"HS256"}' payload = b'{"iss":"joe",\r\n "exp":1300819380,' b'\r\n "http://example.com/is_root":true}' sign_input = b64e(header) + b"." + b64e(payload) sig = signer.sign(sign_input, hmac) assert b64e(sig) == b"dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
def test_setup_auth_session_revoked(self): request = AuthorizationRequest( client_id="client_id", redirect_uri="https://rp.example.com/cb", response_type=["id_token"], state="state", nonce="nonce", scope="openid", ) redirect_uri = request["redirect_uri"] cinfo = { "client_id": "client_id", "redirect_uris": [("https://rp.example.com/cb", {})], "id_token_signed_response_alg": "RS256", } _ec = self.endpoint.server_get("endpoint_context") session_id = self._create_session(request) item = _ec.authn_broker.db["anon"] item["method"].user = b64e(as_bytes(json.dumps({"uid": "krall", "sid": session_id}))) grant = _ec.session_manager[session_id] grant.revoked = True res = self.endpoint.setup_auth(request, redirect_uri, cinfo, None) assert set(res.keys()) == {"args", "function"}
def test_a_1_1b(): payload = b'{"iss":"joe",\r\n "exp":1300819380,' \ b'\r\n "http://example.com/is_root":true}' val = b64e(payload) assert val == ( b'eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9' b'leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ')
def test_setup_auth_session_revoked(self): request = AuthorizationRequest( client_id="client_id", redirect_uri="https://rp.example.com/cb", response_type=["id_token"], state="state", nonce="nonce", scope="openid", ) redirect_uri = request["redirect_uri"] cinfo = { "client_id": "client_id", "redirect_uris": [("https://rp.example.com/cb", {})], "id_token_signed_response_alg": "RS256", } _ec = self.endpoint.endpoint_context _ec.sdb["session_id"] = SessionInfo( authn_req=request, uid="diana", sub="abcdefghijkl", authn_event={ "authn_info": "loa1", "uid": "diana", "authn_time": utc_time_sans_frac(), }, revoked=True, ) item = _ec.authn_broker.db["anon"] item["method"].user = b64e( as_bytes(json.dumps({"uid": "krall", "sid": "session_id"})) ) res = self.endpoint.setup_auth(request, redirect_uri, cinfo, None) assert set(res.keys()) == {"args", "function"}
def modify_header(token, **kwargs): part = token.split('.') _txt = utils.b64d(as_bytes(part[0])) header = json.loads(as_unicode(_txt)) header.update(kwargs) part[0] = utils.b64e(as_bytes(json.dumps(header))) return b'.'.join([as_bytes(p) for p in part])
def new_cookie(endpoint_context, cookie_name=None, typ="sso", **kwargs): if endpoint_context.cookie_dealer: _val = as_unicode(b64e(as_bytes(json.dumps(kwargs)))) return endpoint_context.cookie_dealer.create_cookie( _val, typ=typ, cookie_name=cookie_name, ttl=endpoint_context.sso_ttl ) else: return None
def pem_to_jwk_dict(pem_data: str): """Read PEM certificate and return JWK dictionary""" public_key = import_public_key_from_pem_data(pem_data) if isinstance(public_key, rsa.RSAPublicKey): jwk = RSAKey().load_key(public_key) elif isinstance(public_key, ec.EllipticCurvePublicKey): jwk = ECKey().load_key(public_key) else: raise ValueError("Unknown key type") jwk_dict = jwk.serialize() cert = x509.load_pem_x509_certificate(pem_data.encode(), default_backend()) fp = cert.fingerprint(hashes.SHA256()) jwk_dict["kid"] = b64e(fp[:8]).decode() jwk_dict["x5t#S256"] = b64e(fp).decode() jwk_dict["x5a"] = { "subject": cert.subject.rfc4514_string(), "issuer": cert.issuer.rfc4514_string(), "serial": cert.serial_number, } return jwk_dict
def test_encryption_key(): sk = SYMKey(key="df34db91c16613deba460752522d28f6ebc8a73d0d9185836270c26b") _enc = sk.encryption_key(alg="A128KW") _v = as_unicode(b64e(_enc)) assert _v == "xCo9VhtommCTGMWi-RyWBw" sk = SYMKey(key="df34db91c16613deba460752522d28f6ebc8a73d0d9185836270c26b") _enc = sk.encryption_key(alg="A192KW") _v = as_unicode(b64e(_enc)) assert _v == "xCo9VhtommCTGMWi-RyWB14GQqHAGC86" sk = SYMKey(key="df34db91c16613deba460752522d28f6ebc8a73d0d9185836270c26b") _enc = sk.encryption_key(alg="A256KW") _v = as_unicode(b64e(_enc)) assert _v == "xCo9VhtommCTGMWi-RyWB14GQqHAGC86vweU_Pi62X8" ek = sha256_digest( "YzE0MjgzNmRlODI5Yzg2MGYyZTRjNGE0NTZlMzBkZDRiNzJkNDA5MzUzNjM0ODkzM2E2MDk3ZWY" )[:16] assert as_unicode(b64e(ek)) == "yf_UUkAFZ8Pn_prxPPgu9w" sk = SYMKey( key= "YzE0MjgzNmRlODI5Yzg2MGYyZTRjNGE0NTZlMzBkZDRiNzJkNDA5MzUzNjM0ODkzM2E2MDk3ZWY" ) _enc = sk.encryption_key(alg="A128KW") _v = as_unicode(b64e(_enc)) assert _v == as_unicode(b64e(ek))
def modify_json_message(token): part = [as_bytes(p) for p in token.split('.')] _txt = utils.b64d(part[1]) msg = json.loads(as_unicode(_txt)) for k, v in msg.items(): msg_copy = msg.copy() del msg_copy[k] for _k in modify_str(k): msg_copy[_k] = v part[1] = utils.b64e(as_bytes(json.dumps(msg_copy))) yield b'.'.join([as_bytes(p) for p in part]) if isinstance(v, str): for _v in modify_str(v): msg_copy[k] = _v part[1] = utils.b64e(as_bytes(json.dumps(msg_copy))) yield b'.'.join([as_bytes(p) for p in part]) elif isinstance(v, int): _v = v + 1 msg_copy[k] = _v part[1] = utils.b64e(as_bytes(json.dumps(msg_copy))) yield b'.'.join([as_bytes(p) for p in part])
def x5t_calculation(cert): """ base64url-encoded SHA-1 thumbprint (a.k.a. digest) of the DER encoding of an X.509 certificate. :param cert: DER encoded X.509 certificate :return: x5t value """ if isinstance(cert, str): der_cert = base64.b64decode(cert.encode("ascii")) else: der_cert = base64.b64decode(cert) return b64e(hashlib.sha1(der_cert).digest())
def add_code_challenge(request_args, service, **kwargs): """ PKCE RFC 7636 support To be added as a post_construct method to an :py:class:`oidcservice.oidc.service.Authorization` instance :param service: The service that uses this function :param request_args: Set of request arguments :param kwargs: Extra set of keyword arguments :return: Updated set of request arguments """ _kwargs = service.service_context.add_on["pkce"] try: cv_len = _kwargs['code_challenge_length'] except KeyError: cv_len = 64 # Use default # code_verifier: string of length cv_len code_verifier = unreserved(cv_len) _cv = code_verifier.encode() try: _method = _kwargs['code_challenge_method'] except KeyError: _method = 'S256' try: # Pick hash method _hash_method = CC_METHOD[_method] # Use it on the code_verifier _hv = _hash_method(_cv).digest() # base64 encode the hash value code_challenge = b64e(_hv).decode('ascii') except KeyError: raise Unsupported( 'PKCE Transformation method:{}'.format(_method)) _item = Message(code_verifier=code_verifier, code_challenge_method=_method) service.store_item(_item, 'pkce', request_args['state']) request_args.update( { "code_challenge": code_challenge, "code_challenge_method": _method }) return request_args, {}
def process_hc1_cwt(signed_data: bytes, public_keys): res = verify(signed_data=signed_data, public_keys=public_keys) logger.info("Signatured issued by: %s", res.iss) logger.info("Signature verified by: %s", b64e(res.kid).decode()) logger.info("Signatured issued at: %s", res.iat) if res.expired: logger.warning("Signatured expired at: %s", res.exp) else: logger.info("Signatured expires at: %s", res.exp) if res.eu_dgc_v1 is None: logger.warning("No EU HCERT version 1 found in payload") logger.info("Verified payload: %s", json.dumps(res.eu_dgc_v1, indent=4))
def command_verify(args: argparse.Namespace): """Verify signed EHC""" public_keys = [] if args.jwks: with open(args.jwks) as jwks_file: jwks = json.load(jwks_file) for jwk_dict in jwks.get("keys", []): key = cosekey_from_jwk_dict(jwk_dict, private=False) key.issuer = jwk_dict.get("issuer") public_keys.append(key) elif args.key: public_keys = [read_cosekey(args.key, private=False)] if args.kid: public_key.kid = b64d(args.kid.encode()) with open(args.input, "rb") as input_file: signed_data = input_file.read() res = verify(signed_data=signed_data, public_keys=public_keys) logger.info("Signatured issued by: %s", res.iss) logger.info( "Signature verified by: %s (%s)", b64e(res.kid).decode(), res.key.issuer if hasattr(res.key, "issuer") else None, ) logger.info("Signatured issued at: %s", res.iat) if res.expired: logger.warning("Signatured expired at: %s", res.exp) else: logger.info("Signatured expires at: %s", res.exp) if res.eu_dgc_v1 is None: logger.warning("No EU DCC version 1 found in payload") if args.output: with open(args.output, "wt") as output_file: json.dump(res.eu_dgc_v1, output_file, indent=4) else: logger.info("Verified payload: %s", json.dumps(res.eu_dgc_v1, indent=4))
def _code_challenge(): """ PKCE aka RFC 7636 """ # code_verifier: string of length cv_len code_verifier = unreserved(64) _cv = code_verifier.encode() _method = "S256" # Pick hash method _hash_method = CC_METHOD[_method] # Use it on the code_verifier _hv = _hash_method(_cv).digest() # base64 encode the hash value code_challenge = b64e(_hv).decode("ascii") return { "code_challenge": code_challenge, "code_challenge_method": _method, "code_verifier": code_verifier, }
def get_channel_contents(config: dict, name: str, contents: dict): """Publish channel contents on MQTT""" if name in config: channel_topic = config[name]["topic"] channel_format = config[name]["format"] if channel_format == "json": new_contents = {} for key, value in contents.items(): if key.startswith(FILE_PREFIX): key = key[len(FILE_PREFIX):] with open(value, "rb") as input_file: value = input_file.read() if key.startswith(BASE64_PREFIX): key = key[len(BASE64_PREFIX):] value = b64e(value) value = value.decode() new_contents[key] = value payload = json.dumps(new_contents).encode() elif channel_format == "nmea": payload = contents_to_nmea(contents).encode() elif channel_format == "bytes": if "base64" in contents: payload = b64d(contents["base64"]) elif "file" in contents: filename = contents["file"] with open(filename, "rb") as input_file: payload = input_file.read() elif "string" in contents: payload = contents["string"].encode() else: raise Exception("No binary contents found") else: raise Exception("Undefined format: {}".format(channel_format)) return (channel_topic, payload) else: raise Exception("Undefined channel: {}".format(name))
def main(): parser = argparse.ArgumentParser(description="CWT dump tool") parser.add_argument( "file", help="File with CWT contents", ) args = parser.parse_args() with open(args.file, "rb") as cwt_file: cwt_bytes = cwt_file.read() cwt_cbor = cbor2.loads(cwt_bytes) phdr = cbor2.loads(cwt_cbor.value[0]) if cwt_cbor.value[0] else None try: uhdr = cbor2.loads(cwt_cbor.value[1]) if cwt_cbor.value[1] else None except TypeError as exc: print("Exception:", exc) print("Unprotected header:", cwt_cbor.value[1]) uhdr = None message = cbor2.loads(cwt_cbor.value[2]) signature = cwt_cbor.value[3] print("Protected header:") print_header(phdr) print("Unprotected header:") print_header(uhdr) print("Message:") print_message(message) print("Signature:", b64e(signature).decode())
def test_setup_auth_user(self): request = AuthorizationRequest( client_id="client_id", redirect_uri="https://rp.example.com/cb", response_type=["id_token"], state="state", nonce="nonce", scope="openid", ) redirect_uri = request["redirect_uri"] cinfo = { "client_id": "client_id", "redirect_uris": [("https://rp.example.com/cb", {})], "id_token_signed_response_alg": "RS256", } session_id = self._create_session(request) item = self.endpoint.server_get("endpoint_context").authn_broker.db["anon"] item["method"].user = b64e(as_bytes(json.dumps({"uid": "krall", "sid": session_id}))) res = self.endpoint.setup_auth(request, redirect_uri, cinfo, None) assert set(res.keys()) == {"session_id", "identity", "user"} assert res["identity"]["uid"] == "krall"
def modify_signature(token): part = [as_bytes(p) for p in token.split('.')] signature = utils.b64d(part[2]) for sig in modify_bytes(signature): part[2] = utils.b64e(sig) yield b'.'.join([as_bytes(p) for p in part])
"""Test BoB Validation API""" import unittest import logging import os from cryptojwt.utils import b64e from bobby_client.env import TestEnvironment ISSUER_SIGNATURE_FAST = b64e(os.urandom(32)).decode() ISSUER_SIGNATURE_SLOW = b64e(os.urandom(32)).decode() # Lillies väg 2, Lerum EVENT_START_FAST = { "eventType": "validation", "ticketId": "TICKET_ID", "mtbReference": { "pid": 1, "issuerSignature": ISSUER_SIGNATURE_FAST }, 'time': '20170521T200000Z', 'modeOfTransport': 'bus', 'geo': { 'lat': 57.770351, 'long': 12.255959 } } # Lillies väg 2, Lerum EVENT_START_SLOW = { "eventType": "validation",
def _encrypt_sid(self, sid): encrypter = AES_GCMEncrypter(key=as_bytes(self.server_get("endpoint_context").symkey)) enc_msg = encrypter.encrypt(as_bytes(sid), iv=self.iv) return as_unicode(b64e(enc_msg))
def setUp(self): logging.basicConfig(level=logging.DEBUG) self.env = TestEnvironment.create_from_config_file() self.did = b64e(str(uuid.uuid4()).encode()).decode() self.session = self.env.get_session() self.env.authenticate(self.session, api='device')
def authz_part2(self, user, authn_event, request, **kwargs): """ After the authentication this is where you should end up :param user: :param request: The Authorization Request :param sid: Session key :param kwargs: possible other parameters :return: A redirect to the redirect_uri of the client """ sid = setup_session(self.endpoint_context, request, user, authn_event=authn_event) try: resp_info = self.post_authentication(user, request, sid, **kwargs) except Exception as err: return self.error_response({}, "server_error", err) if "check_session_iframe" in self.endpoint_context.provider_info: ec = self.endpoint_context salt = rndstr() if not ec.sdb.is_session_revoked(sid): authn_event = ec.sdb.get_authentication_event( sid) # use the last session _state = b64e( as_bytes( json.dumps({"authn_time": authn_event["authn_time"]}))) session_cookie = ec.cookie_dealer.create_cookie( as_unicode(_state), typ="session", cookie_name=ec.cookie_name["session_management"], same_site="None", http_only=False) opbs = session_cookie[ec.cookie_name["session_management"]] logger.debug( "compute_session_state: client_id=%s, origin=%s, opbs=%s, salt=%s", request["client_id"], resp_info["return_uri"], opbs.value, salt, ) _session_state = compute_session_state(opbs.value, salt, request["client_id"], resp_info["return_uri"]) if "cookie" in resp_info: if isinstance(resp_info["cookie"], list): resp_info["cookie"].append(session_cookie) else: append_cookie(resp_info["cookie"], session_cookie) else: resp_info["cookie"] = session_cookie resp_info["response_args"]["session_state"] = _session_state # Mix-Up mitigation resp_info["response_args"]["iss"] = self.endpoint_context.issuer resp_info["response_args"]["client_id"] = request["client_id"] return resp_info
def test_a_1_1a(): header = b'{"typ":"JWT",\r\n "alg":"HS256"}' val = b64e(header) assert val == b"eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9"
def wrapper(code_verifier): _h = f(code_verifier.encode("ascii")).digest() _cc = b64e(_h) return _cc.decode("ascii")
import sys from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptojwt.utils import b64e pem_data = sys.stdin.read() cert = x509.load_pem_x509_certificate(pem_data.encode(), default_backend()) fp = cert.fingerprint(hashes.SHA256()) print(b64e(fp[:8]).decode())
def test_jwe_09_a1(): # RSAES OAEP and AES GCM msg = b"The true sign of intelligence is not knowledge but imagination." # A.1.1 header = b'{"alg":"RSA-OAEP","enc":"A256GCM"}' b64_header = b64e(header) # A.1.2 assert b64_header == b"eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkEyNTZHQ00ifQ" # A.1.3 cek = intarr2bytes([ 177, 161, 244, 128, 84, 143, 225, 115, 63, 180, 3, 255, 107, 154, 212, 246, 138, 7, 110, 91, 112, 46, 34, 105, 47, 130, 203, 46, 122, 234, 64, 252 ]) # A.1.4 Key Encryption # enc_key = [ # 56, 163, 154, 192, 58, 53, 222, 4, 105, 218, 136, 218, 29, 94, 203, # 22, 150, 92, 129, 94, 211, 232, 53, 89, 41, 60, 138, 56, 196, 216, # 82, 98, 168, 76, 37, 73, 70, 7, 36, 8, 191, 100, 136, 196, 244, 220, # 145, 158, 138, 155, 4, 117, 141, 230, 199, 247, 173, 45, 182, 214, # 74, 177, 107, 211, 153, 11, 205, 196, 171, 226, 162, 128, 171, 182, # 13, 237, 239, 99, 193, 4, 91, 219, 121, 223, 107, 167, 61, 119, 228, # 173, 156, 137, 134, 200, 80, 219, 74, 253, 56, 185, 91, 177, 34, 158, # 89, 154, 205, 96, 55, 18, 138, 43, 96, 218, 215, 128, 124, 75, 138, # 243, 85, 25, 109, 117, 140, 26, 155, 249, 67, 167, 149, 231, 100, 6, # 41, 65, 214, 251, 232, 87, 72, 40, 182, 149, 154, 168, 31, 193, 126, # 215, 89, 28, 111, 219, 125, 182, 139, 235, 195, 197, 23, 234, 55, 58, # 63, 180, 68, 202, 206, 149, 75, 205, 248, 176, 67, 39, 178, 60, 98, # 193, 32, 238, 122, 96, 158, 222, 57, 183, 111, 210, 55, 188, 215, # 206, 180, 166, 150, 166, 106, 250, 55, 229, 72, 40, 69, 214, 216, # 104, 23, 40, 135, 212, 28, 127, 41, 80, 175, 174, 168, 115, 171, 197, # 89, 116, 92, 103, 246, 83, 216, 182, 176, 84, 37, 147, 35, 45, 219, # 172, 99, 226, 233, 73, 37, 124, 42, 72, 49, 242, 35, 127, 184, 134, # 117, 114, 135, 206] b64_ejek = b'ApfOLCaDbqs_JXPYy2I937v_xmrzj' \ b'-Iss1mG6NAHmeJViM6j2l0MHvfseIdHVyU2BIoGVu9ohvkkWiRq5DL2jYZTPA9TAdwq3FUIVyoH-Pedf6elHIVFi2KGDEspYMtQARMMSBcS7pslx6flh1Cfh3GBKysztVMEhZ_maFkm4PYVCsJsvq6Ct3fg2CJPOs0X1DHuxZKoIGIqcbeK4XEO5a0h5TAuJObKdfO0dKwfNSSbpu5sFrpRFwV2FTTYoqF4zI46N9-_hMIznlEpftRXhScEJuZ9HG8C8CHB1WRZ_J48PleqdhF4o7fB5J1wFqUXBtbtuGJ_A2Xe6AEhrlzCOw' iv = intarr2bytes([227, 197, 117, 252, 2, 219, 233, 68, 180, 225, 77, 219]) aadp = b64_header + b'.' + b64_ejek gcm = AES_GCMEncrypter(key=cek) ctxt, tag = split_ctx_and_tag(gcm.encrypt(msg, iv, aadp)) _va = to_intarr(ctxt) assert _va == [ 229, 236, 166, 241, 53, 191, 115, 196, 174, 43, 73, 109, 39, 122, 233, 96, 140, 206, 120, 52, 51, 237, 48, 11, 190, 219, 186, 80, 111, 104, 50, 142, 47, 167, 59, 61, 181, 127, 196, 21, 40, 82, 242, 32, 123, 143, 168, 226, 73, 216, 176, 144, 138, 247, 106, 60, 16, 205, 160, 109, 64, 63, 192 ] assert bytes2intarr(tag) == [ 130, 17, 32, 198, 120, 167, 144, 113, 0, 50, 158, 49, 102, 208, 118, 152 ] # tag = long2hexseq(tag) # iv = long2hexseq(iv) res = b".".join([b64_header, b64_ejek, b64e(iv), b64e(ctxt), b64e(tag)]) # print(res.split(b'.')) expected = b'.'.join([ b'eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkEyNTZHQ00ifQ', b'ApfOLCaDbqs_JXPYy2I937v_xmrzj' b'-Iss1mG6NAHmeJViM6j2l0MHvfseIdHVyU2BIoGVu9ohvkkWiRq5DL2jYZTPA9TAdwq3FUIVyoH-Pedf6elHIVFi2KGDEspYMtQARMMSBcS7pslx6flh1Cfh3GBKysztVMEhZ_maFkm4PYVCsJsvq6Ct3fg2CJPOs0X1DHuxZKoIGIqcbeK4XEO5a0h5TAuJObKdfO0dKwfNSSbpu5sFrpRFwV2FTTYoqF4zI46N9-_hMIznlEpftRXhScEJuZ9HG8C8CHB1WRZ_J48PleqdhF4o7fB5J1wFqUXBtbtuGJ_A2Xe6AEhrlzCOw', b'48V1_ALb6US04U3b', b'5eym8TW_c8SuK0ltJ3rpYIzOeDQz7TALvtu6UG9oMo4vpzs9tX_EFShS8iB7j6jiSdiwkIr3ajwQzaBtQD_A', b'ghEgxninkHEAMp4xZtB2mA' ]) assert res == expected
def authz_part2(self, request, session_id, **kwargs): """ After the authentication this is where you should end up :param request: The Authorization Request :param session_id: Session identifier :param kwargs: possible other parameters :return: A redirect to the redirect_uri of the client """ try: resp_info = self.post_authentication(request, session_id, **kwargs) except Exception as err: return self.error_response({}, "server_error", err) _context = self.server_get("endpoint_context") if "check_session_iframe" in _context.provider_info: salt = rndstr() try: authn_event = _context.session_manager.get_authentication_event( session_id) except KeyError: return self.error_response({}, "server_error", "No such session") else: if authn_event.is_valid() is False: return self.error_response({}, "server_error", "Authentication has timed out") _state = b64e( as_bytes(json.dumps({"authn_time": authn_event["authn_time"]}))) _session_cookie_content = _context.new_cookie( name=_context.cookie_handler.name["session_management"], state=as_unicode(_state), ) opbs_value = _session_cookie_content["value"] logger.debug( "compute_session_state: client_id=%s, origin=%s, opbs=%s, salt=%s", request["client_id"], resp_info["return_uri"], opbs_value, salt, ) _session_state = compute_session_state(opbs_value, salt, request["client_id"], resp_info["return_uri"]) if _session_cookie_content: if "cookie" in resp_info: resp_info["cookie"].append(_session_cookie_content) else: resp_info["cookie"] = [_session_cookie_content] resp_info["response_args"]["session_state"] = _session_state # Mix-Up mitigation resp_info["response_args"]["iss"] = _context.issuer resp_info["response_args"]["client_id"] = request["client_id"] return resp_info