Example #1
0
    def test_rsa_prepare_key_should_be_idempotent(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with open(key_path("testkey_rsa.pub")) as keyfile:
            jwt_pub_key_first = algo.prepare_key(keyfile.read())
            jwt_pub_key_second = algo.prepare_key(jwt_pub_key_first)

        assert jwt_pub_key_first == jwt_pub_key_second
Example #2
0
    def test_rsa_prepare_key_should_be_idempotent(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with open(key_path('testkey_rsa.pub'), 'r') as keyfile:
            jwt_pub_key_first = algo.prepare_key(keyfile.read())
            jwt_pub_key_second = algo.prepare_key(jwt_pub_key_first)

        self.assertEqual(jwt_pub_key_first, jwt_pub_key_second)
Example #3
0
    def test_rsa_prepare_key_should_be_idempotent(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with open(key_path('testkey_rsa.pub'), 'r') as keyfile:
            jwt_pub_key_first = algo.prepare_key(keyfile.read())
            jwt_pub_key_second = algo.prepare_key(jwt_pub_key_first)

        assert jwt_pub_key_first == jwt_pub_key_second
Example #4
0
def include_package(config):
    """Pyramid package include"""

    # add translations
    config.add_translation_dirs('pyams_auth_jwt:locales')

    # add configuration directives
    config.add_request_method(create_jwt_token, 'create_jwt_token')
    config.add_request_method(get_jwt_claims, 'jwt_claims', reify=True)

    # add route predicate
    config.add_view_predicate('jwt_object', JWTTokenObjectPredicate)

    # register new REST API routes
    config.add_route(
        REST_TOKEN_ROUTE,
        config.registry.settings.get('pyams.jwt.rest_token_route',
                                     '/api/auth/jwt/token'))
    config.add_route(
        REST_VERIFY_ROUTE,
        config.registry.settings.get('pyams.jwt.rest_verify_route',
                                     '/api/auth/jwt/verify'))

    # update JWT algorithms
    try:
        import pycrypto  # pylint: disable=import-outside-toplevel,unused-import
    except ImportError:
        pass
    else:
        from jwt.contrib.algorithms.pycrypto import RSAAlgorithm  # pylint: disable=import-outside-toplevel
        jwt.unregister_algorithm('RS256')
        jwt.register_algorithm('RS256', RSAAlgorithm(RSAAlgorithm.SHA256))
        jwt.unregister_algorithm('RS512')
        jwt.register_algorithm('RS512', RSAAlgorithm(RSAAlgorithm.SHA512))

    try:
        import ecdsa  # pylint: disable=import-outside-toplevel,unused-import
    except ImportError:
        pass
    else:
        from jwt.contrib.algorithms.py_ecdsa import ECAlgorithm  # pylint: disable=import-outside-toplevel
        jwt.unregister_algorithm('ES256')
        jwt.register_algorithm('ES256', ECAlgorithm(ECAlgorithm.SHA256))
        jwt.unregister_algorithm('ES512')
        jwt.register_algorithm('ES512', ECAlgorithm(ECAlgorithm.SHA512))

    try:
        import pyams_zmi  # pylint: disable=import-outside-toplevel,unused-import
        config.scan()
    except ImportError:
        config.scan(ignore='pyams_auth_jwt.zmi')
def jwt_rs256_encoded():
    #read file stage
    f = open(os.path.abspath(private_key_pemfile_path), "r")
    lines = f.read()
    f.close()
    private_key = '\n'.join(lines.split('\\n'))
    print(private_key)

    #encoded stage
    '''
    default request data
    #header
    {
        "alg":"RS256",
        "typ":"JWT"
    }
    #payload
    {
        "some":"payload"
    }
    '''
    jwt.unregister_algorithm('RS256')
    jwt.register_algorithm('RS256', RSAAlgorithm(RSAAlgorithm.SHA256))
    encoded_data = jwt.encode({"some": "payload"},
                              private_key,
                              algorithm='RS256')

    return encoded_data
Example #6
0
def verify_token(token):

    #decrypt the identifying token passed from the cognito userpool, to the front end app, to here
    #more info: http://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html

    # Register RS256 if needed
    try:
        jwt.register_algorithm('RS256', RSAAlgorithm(RSAAlgorithm.SHA256))
    except ValueError:
        # RS256 is registered already
        pass

    #pulls the kid (key ID) from the token
    #to see if it maps to the userpool's JWT set, found at globals.userpool
    #this confirms that the token is from AWS
    kid = get_kid(token)

    if kid not in globals.user_pool:
        get_user_pool()
    # Right now, N and E are base64 encoded.
    n_encoded = get_n_encoded(kid)
    e_encoded = get_e_encoded(kid)

    # Convert into regular 8-bit bytes
    n_decoded = b64decode(format_base64(n_encoded))
    e_decoded = b64decode(format_base64(e_encoded))

    # Convert each byte into length of 2 hexadecimal string
    # Finally concatnate all these strings into one big hex number
    n_hex = '0x' + ''.join(
        ['%02X' % struct.unpack('B', x)[0] for x in n_decoded])
    e_hex = '0x' + ''.join(
        ['%02X' % struct.unpack('B', x)[0] for x in e_decoded])

    # Use python interpreter to eval the big hex number
    # Note that python has unlimited accuracy in big number
    # Numbers will never overflow (Given enough memory)
    n_val = eval(n_hex)
    e_val = eval(e_hex)

    # All these claim fields' descriptions can be found here:
    # https://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#rfc.section.4.1
    verify_options = {
        'verify_signature': True,
        'verify_exp': True,
        'verify_nbf': True,
        'verify_iat': True,
        'verify_aud': False,
        'require_exp': True,
        'require_iat': True,
        'require_nbf': False
    }

    key_pub = RSA.construct((long(n_val), long(e_val)))

    try:
        jwt.decode(token, key=key_pub, options=verify_options)
        return True
    except Exception as e:
        return False
Example #7
0
def generate_jwt(bot_username: str,
                 private_key_path: str,
                 use_legacy_crypto: bool = False):
    # GAE does not allow installation of the cryptography module
    # Thus, I need to provide a way to fall back to the legacy modules
    # required by pyJWT
    if use_legacy_crypto:
        from jwt.contrib.algorithms.pycrypto import RSAAlgorithm
        jwt.unregister_algorithm('RS512')
        jwt.register_algorithm('RS512', RSAAlgorithm(RSAAlgorithm.SHA512))

    header = {"typ": "JWT", "alg": "RS512"}

    # Make sure you're using datetime.utcnow() and not datetime.now()
    payload = {
        "sub": bot_username,
        "exp": datetime.utcnow() + timedelta(minutes=5)
    }

    with open(Path(private_key_path), 'r') as keyfile:
        private_key = keyfile.read()

        return jwt.encode(payload,
                          private_key,
                          algorithm='RS512',
                          headers=header)
def new_jwt_rs1_signing_algorithm():
    global _jwtrs1
    if _jwtrs1 is None:
        from jwt.contrib.algorithms.pycrypto import RSAAlgorithm
        from Crypto.Hash import SHA
        _jwtrs1 = RSAAlgorithm(SHA)
    return _jwtrs1
Example #9
0
    def test_rsa_sign_should_generate_correct_signature_value(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        jwt_message = force_bytes("Hello World!")

        expected_sig = base64.b64decode(
            force_bytes(
                "yS6zk9DBkuGTtcBzLUzSpo9gGJxJFOGvUqN01iLhWHrzBQ9ZEz3+Ae38AXp"
                "10RWwscp42ySC85Z6zoN67yGkLNWnfmCZSEv+xqELGEvBJvciOKsrhiObUl"
                "2mveSc1oeO/2ujkGDkkkJ2epn0YliacVjZF5+/uDmImUfAAj8lzjnHlzYix"
                "sn5jGz1H07jYYbi9diixN8IUhXeTafwFg02IcONhum29V40Wu6O5tAKWlJX"
                "fHJnNUzAEUOXS0WahHVb57D30pcgIji9z923q90p5c7E2cU8V+E1qe8NdCA"
                "APCDzZZ9zQ/dgcMVaBrGrgimrcLbPjueOKFgSO+SSjIElKA=="
            )
        )

        with open(key_path("testkey_rsa")) as keyfile:
            jwt_key = algo.prepare_key(keyfile.read())

        with open(key_path("testkey_rsa.pub")) as keyfile:
            jwt_pub_key = algo.prepare_key(keyfile.read())

        algo.sign(jwt_message, jwt_key)
        result = algo.verify(jwt_message, jwt_pub_key, expected_sig)
        assert result
Example #10
0
    def test_rsa_verify_should_return_true_if_signature_valid(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        jwt_message = ensure_bytes('Hello World!')

        jwt_sig = base64.b64decode(ensure_bytes(
            'yS6zk9DBkuGTtcBzLUzSpo9gGJxJFOGvUqN01iLhWHrzBQ9ZEz3+Ae38AXp'
            '10RWwscp42ySC85Z6zoN67yGkLNWnfmCZSEv+xqELGEvBJvciOKsrhiObUl'
            '2mveSc1oeO/2ujkGDkkkJ2epn0YliacVjZF5+/uDmImUfAAj8lzjnHlzYix'
            'sn5jGz1H07jYYbi9diixN8IUhXeTafwFg02IcONhum29V40Wu6O5tAKWlJX'
            'fHJnNUzAEUOXS0WahHVb57D30pcgIji9z923q90p5c7E2cU8V+E1qe8NdCA'
            'APCDzZZ9zQ/dgcMVaBrGrgimrcLbPjueOKFgSO+SSjIElKA=='))

        with open(key_path('testkey_rsa.pub'), 'r') as keyfile:
            jwt_pub_key = algo.prepare_key(keyfile.read())

        result = algo.verify(jwt_message, jwt_pub_key, jwt_sig)
        assert result
Example #11
0
def _jwt_rs1_signing_algorithm():
    global _jwtrs1
    if _jwtrs1 is None:
        #import jwt.algorithms as jwtalgo
        #_jwtrs1 = jwtalgo.RSAAlgorithm(jwtalgo.hashes.SHA1)
        # Edits to use pycrypto instead of cryptography to get working on GAE
        from jwt.contrib.algorithms.pycrypto import RSAAlgorithm
        from Crypto.Hash import SHA
        _jwtrs1 = RSAAlgorithm(SHA)
    return _jwtrs1
Example #12
0
    def test_rsa_verify_should_return_true_if_signature_valid(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        jwt_message = ensure_bytes('Hello World!')

        jwt_sig = base64.b64decode(
            ensure_bytes(
                'yS6zk9DBkuGTtcBzLUzSpo9gGJxJFOGvUqN01iLhWHrzBQ9ZEz3+Ae38AXp'
                '10RWwscp42ySC85Z6zoN67yGkLNWnfmCZSEv+xqELGEvBJvciOKsrhiObUl'
                '2mveSc1oeO/2ujkGDkkkJ2epn0YliacVjZF5+/uDmImUfAAj8lzjnHlzYix'
                'sn5jGz1H07jYYbi9diixN8IUhXeTafwFg02IcONhum29V40Wu6O5tAKWlJX'
                'fHJnNUzAEUOXS0WahHVb57D30pcgIji9z923q90p5c7E2cU8V+E1qe8NdCA'
                'APCDzZZ9zQ/dgcMVaBrGrgimrcLbPjueOKFgSO+SSjIElKA=='))

        with open(key_path('testkey_rsa.pub'), 'r') as keyfile:
            jwt_pub_key = algo.prepare_key(keyfile.read())

        result = algo.verify(jwt_message, jwt_pub_key, jwt_sig)
        assert result
Example #13
0
def _jwt_rs1_signing_algorithm():
    global _jwtrs1
    if _jwtrs1 is None:
        #import jwt.algorithms as jwtalgo
        #_jwtrs1 = jwtalgo.RSAAlgorithm(jwtalgo.hashes.SHA1)
        # Edits to use pycrypto instead of cryptography to get working on GAE
        # https://github.com/freakboy3742/pyxero/issues/146#issuecomment-274425019
        from jwt.contrib.algorithms.pycrypto import RSAAlgorithm
        from Crypto.Hash import SHA
        _jwtrs1 = RSAAlgorithm(SHA)
    return _jwtrs1
Example #14
0
def setup_module(_module):
    """Perform setup of any state specific to the execution of the given module."""
    global PRIVATE_KEY
    global PUBLIC_KEY

    # private and public key used in tests
    with open("tests/private_key.pem") as fin:
        PRIVATE_KEY = fin.read()

    with open("tests/public_key.pem") as fin:
        PUBLIC_KEY = fin.read()

    # just to make sure the following statement does not raise an exception
    try:
        jwt.unregister_algorithm('RS256')
    except KeyError:
        pass

    # make sure the RS256 algorithm is initialized
    jwt.register_algorithm('RS256', RSAAlgorithm(RSAAlgorithm.SHA256))
Example #15
0
    def test_rsa_should_reject_non_string_key(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with pytest.raises(TypeError):
            algo.prepare_key(None)
Example #16
0
    def test_rsa_should_accept_unicode_key(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with open(key_path('testkey_rsa'), 'r') as rsa_key:
            algo.prepare_key(ensure_unicode(rsa_key.read()))
Example #17
0
    def test_rsa_should_parse_pem_public_key(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with open(key_path('testkey2_rsa.pub.pem'), 'r') as pem_key:
            algo.prepare_key(pem_key.read())
import jwt
import json
from jwt.contrib.algorithms.pycrypto import RSAAlgorithm

from Crypto.Util.asn1 import DerSequence
from Crypto.PublicKey import RSA
from binascii import a2b_base64

from rfc822 import mktime_tz, parsedate_tz
import time

__all__ = ["verify_token"]
""" Try to register algorithm - ignore if it is already registered """
try:
    jwt.register_algorithm("RS256", RSAAlgorithm(RSAAlgorithm.SHA256))
except ValueError:
    pass
""" get certificate for key id, caches the certs using memcache """


def get_certificate(key_id):
    certs = memcache.get(
        key=
        "www.googleapis.com/robot/v1/metadata/x509/[email protected]"
    )

    if certs is None:
        result = urlfetch.fetch(
            "https://www.googleapis.com/robot/v1/metadata/x509/[email protected]",
            validate_certificate=True)
Example #19
0
    def test_rsa_should_reject_non_string_key(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with pytest.raises(TypeError):
            algo.prepare_key(None)
Example #20
0
    def test_rsa_should_parse_pem_public_key(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with open(key_path("testkey2_rsa.pub.pem")) as pem_key:
            algo.prepare_key(pem_key.read())
Example #21
0
    def test_rsa_should_accept_unicode_key(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with open(key_path('testkey_rsa'), 'r') as rsa_key:
            algo.prepare_key(ensure_unicode(rsa_key.read()))
Example #22
0
import os
from collections import OrderedDict
from datetime import datetime, timedelta

import jwt
import pem
import requests
from jwt.contrib.algorithms.pycrypto import RSAAlgorithm


# Revolut auth requires RS256 algorithm need to enable here via pycrypto (can't use cryptography on GAE)
jwt.register_algorithm('RS256', RSAAlgorithm(RSAAlgorithm.SHA256))


class RevolutClient:

    def __init__(self):
        self.base_url = os.environ.get('REVOLUT_URL')

    def generate_jwt(self):

        # args must be in this exact order for the JWT to be valid
        token_args = OrderedDict([
            ("iss", os.environ.get('REVOLUT_JWT_ISSUER')),
            ("sub", os.environ.get('REVOLUT_CLIENT_ID')),
            ("aud", "https://revolut.com"),
            ("iat", datetime.now()),
            ("exp", datetime.now() + timedelta(minutes=60))
        ])

        cert = pem.parse_file(os.environ.get('REVOLUT_PRIVATE_KEY_PATH'))
Example #23
0
    def test_rsa_should_accept_unicode_key(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with open(key_path("testkey_rsa")) as rsa_key:
            algo.prepare_key(force_unicode(rsa_key.read()))
Example #24
0
import logging
import time
import uuid

from jwt import InvalidTokenError, DecodeError
from jwt.exceptions import InvalidKeyError
import jwt

from model import SecretValue
import config
import util

from jwt.contrib.algorithms.pycrypto import RSAAlgorithm

# jwt.unregister_algorithm('RS512')
jwt.register_algorithm('RS512', RSAAlgorithm(RSAAlgorithm.SHA512))


ALGORITHM = 'HS512'
ALGORITHM_RSA = 'RS512'


EXPIRED = 'expired'
NO_USER = '******'
NOT_FOUND = 'not found'
USED = 'used'


def get_secret():
    """Get secret for signing/verifying symmetric token. Defaults to config."""
    sv_entity = SecretValue.get_by_id('jwt_secret')