Exemplo n.º 1
0
def test_a_1_3b():
    _jwt = ("eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJl"
            "eHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0c"
            "nVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk")
    keys = [SYMKey(key=intarr2bin(HMAC_KEY))]
    _jws2 = JWS(alg="")
    _jws2.verify_compact(_jwt, keys)
Exemplo n.º 2
0
def test_jws_mac_authenticator_and_verifier():
    algs = ['HS256', 'HS384', 'HS512']
    for alg in algs:
        calgs = algs[:]
        calgs.remove(alg)

        json_hmac_key = json.loads(test_vector.json_hmac_key)
        json_hmac_key['alg'] = alg
        json_hmac_key = json.dumps(json_hmac_key)
        json_header_hmac = json.loads(test_vector.test_header_hmac)
        json_header_hmac['alg'] = alg
        json_header_hmac = json.dumps(json_header_hmac)

        # Authenticator
        mac_key = key_from_jwk_dict(json.loads(json_hmac_key))
        authenticator = JWS(test_vector.test_payload,
                            **json.loads(json_header_hmac))
        signed_token = authenticator.sign_compact([mac_key])

        # Verify
        verifier = JWS(alg=alg)
        assert verifier.verify_compact(signed_token, [mac_key])
        for modified_token in modify_token(signed_token, calgs):
            with pytest.raises(JWKESTException):
                assert verifier.verify_compact(modified_token, [mac_key])
Exemplo n.º 3
0
def test_jws_rsa_signer_and_verifier():
    algs = ['RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512']
    for alg in algs:
        calgs = algs[:]
        calgs.remove(alg)
        json_priv_key = json.loads(test_vector.json_rsa_priv_key)
        json_priv_key['alg'] = alg
        json_priv_key = json.dumps(json_priv_key)
        json_pub_key = json.loads(test_vector.json_rsa_pub_key)
        json_pub_key['alg'] = alg
        json_pub_key = json.dumps(json_pub_key)

        json_header_rsa = json.loads(test_vector.test_header_rsa)
        json_header_rsa['alg'] = alg

        # Sign
        priv_key = key_from_jwk_dict(json.loads(json_priv_key))
        jws = JWS(msg=test_vector.test_payload, **json_header_rsa)
        signed_token = jws.sign_compact([priv_key])

        # Verify
        pub_key = key_from_jwk_dict(json.loads(json_pub_key))
        verifier = JWS(alg=[alg])
        assert verifier.verify_compact(signed_token, [pub_key])

        for modified_token in modify_token(signed_token, calgs):
            with pytest.raises(JWKESTException):
                verifier.verify_compact(modified_token, [pub_key])
Exemplo n.º 4
0
def test_jws_1():
    msg = {"iss": "joe", "exp": 1300819380, "http://example.com/is_root": True}
    key = SYMKey(key=intarr2bin(HMAC_KEY))
    _jws = JWS(msg, cty="JWT", alg="HS256", jwk=key.serialize())
    res = _jws.sign_compact()

    _jws2 = JWS(alg="HS256")
    _jws2.verify_compact(res, keys=[key])
    assert _jws2.msg == msg
Exemplo n.º 5
0
def test_jws_mm():
    msg = {"iss": "joe", "exp": 1300819380, "http://example.com/is_root": True}
    key = SYMKey(key=intarr2bin(HMAC_KEY))
    _jws = JWS(msg, cty="JWT", alg="HS256", jwk=key.serialize())
    res = _jws.sign_compact()

    _jws2 = JWS(alg="HS512")

    with pytest.raises(SignerAlgError):
        _jws2.verify_compact(res, keys=[key])
Exemplo n.º 6
0
def test_jws_ecdsa_verifier_with_rfc_es512():
    # Set up phase: parse the key and initialize the verifier.
    key = key_from_jwk_dict(json.loads(test_vector.es512_ecdsa_pub_key))
    verifier = JWS(alg='ES512')

    # Use phase
    assert verifier.verify_compact(test_vector.es512_ecdsa_token, [key])
    for modified_token in modify_token(test_vector.es512_ecdsa_token,
                                       ['ES256', 'ES512']):
        with pytest.raises(JWKESTException):
            verifier.verify_compact(modified_token, [key])
Exemplo n.º 7
0
def test_jws_mac_verifier_with_rfc():
    # Set up phase: parse the key and initialize the JwsMacVerify
    key = key_from_jwk_dict(json.loads(test_vector.json_hmac_key))
    verifier = JWS(alg='HS256')

    # Use phase
    assert verifier.verify_compact(test_vector.hmac_token, [key])
    for modified_token in modify_token(test_vector.hmac_token,
                                       ['HS384', 'HS512']):
        with pytest.raises(JWKESTException):
            assert verifier.verify_compact(modified_token, [key])
Exemplo n.º 8
0
def test_jws_rsa_verifier_with_rfc():
    # Set up phase: parse the key and initialize the verifier.
    key = key_from_jwk_dict(json.loads(test_vector.json_rsa_pub_key))
    jws = JWS()

    assert jws.verify_compact(test_vector.rsa_token, [key])

    # mess with the JWS
    for _token in modify_token(test_vector.rsa_token,
                               ['RS384', 'RS512', 'PS256', 'PS384', 'PS512']):
        with pytest.raises(JWKESTException):
            jws.verify_compact(_token, [key])
Exemplo n.º 9
0
def test_jws_ecdsa_signer_verifier_es256():
    # Sign
    priv_key = key_from_jwk_dict(json.loads(test_vector.es256_ecdsa_priv_key))
    signer = JWS(msg=test_vector.test_payload,
                 **json.loads(test_vector.test_header_ecdsa))
    signed_token = signer.sign_compact([priv_key])

    # Verify
    pub_key = key_from_jwk_dict(json.loads(test_vector.es256_ecdsa_pub_key))
    verifier = JWS(alg='ES256')
    assert verifier.verify_compact(signed_token, [pub_key])
    for modified_token in modify_token(signed_token, ['ES384', 'ES512']):
        with pytest.raises(JWKESTException):
            verifier.verify_compact(modified_token, [pub_key])
Exemplo n.º 10
0
def test_signer_ps256_fail():
    payload = "Please take a moment to register today"
    _pkey = import_private_rsa_key_from_file(PRIV_KEY)
    keys = [RSAKey(priv_key=_pkey)]
    # keys[0]._keytype = "private"
    _jws = JWS(payload, alg="PS256")
    _jwt = _jws.sign_compact(keys)[:-5] + "abcde"

    vkeys = [RSAKey(pub_key=_pkey.public_key())]
    _rj = JWS(alg="PS256")
    try:
        _rj.verify_compact(_jwt, vkeys)
    except BadSignature:
        pass
    else:
        assert False
Exemplo n.º 11
0
def test_signer_protected_headers():
    payload = "Please take a moment to register today"
    eck = ec.generate_private_key(ec.SECP256R1(), default_backend())
    _key = ECKey().load_key(eck)
    keys = [_key]
    _jws = JWS(payload, alg="ES256")
    protected = dict(header1=u"header1 is protected",
                     header2="header2 is protected too",
                     a=1)
    _jwt = _jws.sign_compact(keys, protected=protected)

    exp_protected = protected.copy()
    exp_protected["alg"] = "ES256"
    enc_header, enc_payload, sig = _jwt.split(".")
    assert json.loads(b64d(
        enc_header.encode("utf-8")).decode("utf-8")) == exp_protected
    assert b64d(enc_payload.encode("utf-8")).decode("utf-8") == payload

    _pub_key = ECKey().load_key(eck.public_key())
    _rj = JWS(alg="ES256")
    info = _rj.verify_compact(_jwt, [_pub_key])
    assert info == payload
    # Protected by default
    protected["alg"] = "ES256"
    assert _rj.protected_headers() == protected
Exemplo n.º 12
0
    def test_client_secret_jwt(self, services):
        _service_context = services['accesstoken'].service_context
        _service_context.token_endpoint = "https://example.com/token"
        _service_context.set(
            'provider_info', {
                'issuer': 'https://example.com/',
                'token_endpoint': "https://example.com/token"
            })

        csj = ClientSecretJWT()
        request = AccessTokenRequest()

        csj.construct(request,
                      service=services['accesstoken'],
                      algorithm="HS256",
                      authn_endpoint='userinfo')
        assert request["client_assertion_type"] == JWT_BEARER
        assert "client_assertion" in request
        cas = request["client_assertion"]

        _kj = KeyJar()
        _kj.add_symmetric(_service_context.get('client_id'),
                          _service_context.get('client_secret'),
                          usage=['sig'])
        jso = JWT(key_jar=_kj, sign_alg='HS256').unpack(cas)
        assert _eq(jso.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"])

        _rj = JWS(alg='HS256')
        info = _rj.verify_compact(
            cas,
            _kj.get_signing_key(issuer_id=_service_context.get('client_id')))

        assert _eq(info.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"])
        assert info['aud'] == [_service_context.get('provider_info')['issuer']]
Exemplo n.º 13
0
def test_hmac_512():
    payload = "Please take a moment to register today"
    keys = [SYMKey(key=b"My hollow echo chamber", alg="HS512")]
    _jws = JWS(payload, alg="HS512")
    _jwt = _jws.sign_compact(keys)

    _rj = JWS(alg="HS512")
    info = _rj.verify_compact(_jwt, keys)
    assert info == payload
Exemplo n.º 14
0
def test_hmac_from_keyrep():
    payload = "Please take a moment to register today"
    symkeys = [k for k in SIGJWKS if k.kty == "oct"]
    _jws = JWS(payload, alg="HS512")
    _jwt = _jws.sign_compact(symkeys)

    _rj = JWS(alg="HS512")
    info = _rj.verify_compact(_jwt, symkeys)
    assert info == payload
Exemplo n.º 15
0
def test_signer_es(ec_func, alg):
    payload = "Please take a moment to register today"
    eck = ec.generate_private_key(ec_func(), default_backend())
    keys = [ECKey().load_key(eck)]
    _jws = JWS(payload, alg=alg)
    _jwt = _jws.sign_compact(keys)

    _pubkey = ECKey().load_key(eck.public_key())
    _rj = JWS(alg=alg)
    info = _rj.verify_compact(_jwt, [_pubkey])
    assert info == payload
Exemplo n.º 16
0
def test_signer_ps384():
    payload = "Please take a moment to register today"
    _pkey = import_private_rsa_key_from_file(PRIV_KEY)
    keys = [RSAKey(priv_key=_pkey)]
    # keys[0]._keytype = "private"
    _jws = JWS(payload, alg="PS384")
    _jwt = _jws.sign_compact(keys)

    vkeys = [RSAKey(pub_key=_pkey.public_key())]
    _rj = JWS(alg="PS384")
    info = _rj.verify_compact(_jwt, vkeys)
    assert info == payload
Exemplo n.º 17
0
def test_jws_verifier_with_kid():
    # Sign
    priv_key = key_from_jwk_dict(
        json.loads(test_vector.test_json_ecdsa_priv_key_kid1))

    signer = JWS(test_vector.test_payload,
                 **json.loads(test_vector.test_header_ecdsa_kid1))
    signed_token_kid1 = signer.sign_compact([priv_key])

    priv_key = key_from_jwk_dict(
        json.loads(test_vector.test_json_ecdsa_priv_key_kid2))
    signer = JWS(test_vector.test_payload,
                 **json.loads(test_vector.test_header_ecdsa_kid2))
    signed_token_kid2 = signer.sign_compact([priv_key])

    # Verify
    pub_key = key_from_jwk_dict(
        json.loads(test_vector.test_json_ecdsa_pub_key_kid1))

    verifier = JWS(alg='ES256')
    assert verifier.verify_compact(signed_token_kid1, [pub_key])
    # The signature is valid but the kids don't match.
    with pytest.raises(NoSuitableSigningKeys):
        verifier.verify_compact(signed_token_kid2, [pub_key])
Exemplo n.º 18
0
def test_1():
    claimset = {
        "iss": "joe",
        "exp": 1300819380,
        "http://example.com/is_root": True
    }

    _jws = JWS(claimset, cty="JWT", alg="none")
    _jwt = _jws.sign_compact()

    _jr = JWS()
    _msg = _jr.verify_compact(_jwt, allow_none=True)
    print(_jr)
    assert _jr.jwt.headers["alg"] == "none"
    assert _msg == claimset
Exemplo n.º 19
0
def test_rs256_rm_signature():
    payload = "Please take a moment to register today"
    _pkey = import_private_rsa_key_from_file(PRIV_KEY)
    keys = [RSAKey(priv_key=_pkey)]
    # keys[0]._keytype = "private"
    _jws = JWS(payload, alg="RS256")
    _jwt = _jws.sign_compact(keys)

    p = _jwt.split(".")
    _jwt = ".".join(p[:-1])

    vkeys = [RSAKey(key=_pkey.public_key())]
    _rj = JWS()
    try:
        _ = _rj.verify_compact(_jwt, vkeys)
    except WrongNumberOfParts:
        pass
    else:
        assert False
    def test_client_secret_jwt(self, entity):
        _service_context = entity.client_get("service_context")
        _service_context.token_endpoint = "https://example.com/token"

        _service_context.provider_info = {
            'issuer': 'https://example.com/',
            'token_endpoint': "https://example.com/token"
        }

        _service_context.registration_response = {
            'token_endpoint_auth_signing_alg': "HS256"
        }

        csj = ClientSecretJWT()
        request = AccessTokenRequest()

        csj.construct(request,
                      service=entity.client_get("service", 'accesstoken'),
                      authn_endpoint='token_endpoint')
        assert request["client_assertion_type"] == JWT_BEARER
        assert "client_assertion" in request
        cas = request["client_assertion"]

        _kj = KeyJar()
        _kj.add_symmetric(_service_context.client_id,
                          _service_context.client_secret, ['sig'])
        jso = JWT(key_jar=_kj, sign_alg='HS256').unpack(cas)
        assert _eq(jso.keys(), ["aud", "iss", "sub", "exp", "iat", 'jti'])

        _rj = JWS(alg='HS256')
        info = _rj.verify_compact(
            cas, _kj.get_signing_key(issuer_id=_service_context.client_id))

        assert _eq(info.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"])
        assert info['aud'] == [
            _service_context.provider_info['token_endpoint']
        ]
Exemplo n.º 21
0
def test_jws_verifier_with_multiple_keys():
    # Set up phase: parse the keys and initialize the verifier.
    jwks = KeyBundle(json.loads(test_vector.json_pub_keys))
    keys = jwks.keys()

    verifier = JWS(alg='RS256')
    assert verifier.verify_compact(test_vector.rsa_token, keys)
    for modified_token in modify_token(
            test_vector.rsa_token,
        ['RS384', 'RS512', 'PS256', 'PS384', 'PS512']):
        with pytest.raises(JWKESTException):
            verifier.verify_compact(modified_token, keys)

    verifier = JWS(alg='ES256')
    assert verifier.verify_compact(test_vector.es256_ecdsa_token, keys)
    for modified_token in modify_token(test_vector.es256_ecdsa_token,
                                       ['ES384', 'ES512']):
        with pytest.raises(JWKESTException):
            verifier.verify_compact(modified_token, keys)