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
예제 #2
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)
예제 #3
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
예제 #4
0
    def __init__(self, config, trustmodel):
        super(BaseSSI, self).__init__()

        # Setup jwt ES256K algorithm for token decoding verification and encoding
        try:
            jwt.register_algorithm('ES256K', ECAlgorithm(ECAlgorithm.SHA256))
        except ValueError as ve:
            log.debug(str(ve))

        self.comm = uPortWS(config['proxy_url'], config['appname'],
                            config['appid'], config['key'])
        self.appid = config['appid']
        self.trustmodel = trustmodel
예제 #5
0
    def _check_jwt_support(self, algorithm=AuthMetadataAlgorithm.UNSPECIFIED):
        """Ensures JWT and possible dependencies are available."""
        if not HAVE_JWT:
            raise InvalidArgumentError(
                "JWT authorization method requires PyJWT")

        try:
            if algorithm != AuthMetadataAlgorithm.UNSPECIFIED:
                jwt.register_algorithm(algorithm.value.upper(), None)

        except TypeError:
            raise InvalidArgumentError(
                "Algorithm not supported for JWT decoding: [{}]".format(
                    self._algorithm))

        except ValueError:
            pass
예제 #6
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))
예제 #7
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 test_verify_jwt_with_none_algorithm(self):
     """ tests that verify_jwt does not accept jwt that use the none
         algorithm.
     """
     verifier = self._setup_jwt_auth_verifier(self._public_key_pem)
     private_key_ret = atlassian_jwt_auth.key.StaticPrivateKeyRetriever(
         self._example_key_id, self._private_key_pem.decode())
     jwt_signer = NoneAlgorithmJwtAuthSigner(
         issuer=self._example_issuer,
         private_key_retriever=private_key_ret,
     )
     for algorithm in ['none', 'None', 'nOne', 'nonE', 'NONE']:
         if algorithm != 'none':
             jwt.register_algorithm(algorithm,
                                    jwt.algorithms.NoneAlgorithm())
         jwt_token = jwt_signer.generate_jwt(self._example_aud,
                                             alg_header=algorithm)
         if algorithm != 'none':
             jwt.unregister_algorithm(algorithm)
         jwt_headers = jwt.get_unverified_header(jwt_token)
         self.assertEqual(jwt_headers['alg'], algorithm)
         with self.assertRaises(jwt.exceptions.InvalidAlgorithmError):
             verifier.verify_jwt(jwt_token, self._example_aud)
예제 #9
0
import os
from config import LAYER
from datetime import timedelta, datetime

try:
    from Crypto.PublicKey import RSA
except:
    raise Exception("pycrytpo library not installed. "
                    "Run `pip install -r requirements.txt`")

# The PyJWT library can optionally use PyCrypto for RSA256 signing, instead of
#   the 'cryptography' module. We'll use PyCrypto to minimize required external
#   dependencies.
from jwt.contrib.algorithms.pycrypto import RSAAlgorithm
try:
    jwt.register_algorithm('RS256', RSAAlgorithm(RSAAlgorithm.SHA256))
except ValueError:
    pass  # You have cryptography module installed, so we'll use it instead

PROVIDER_ID = LAYER['provider_id']
KEY_ID = LAYER['key_id']
RSA_KEY_PATH = LAYER['rsa_key_path']

if not (PROVIDER_ID and KEY_ID and RSA_KEY_PATH):
    raise Exception("You must provide PROVIDER_ID, KEY_ID, and "
                    "RSA_KEY_PATH in %s" % __file__)

def generate_identity_token(user_id, nonce):
    """Creates Layer Identity Token
    :Parameter user_id:   Your (the Provider) ID that represents the user.
    :Type user_id: string
예제 #10
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'))
예제 #11
0
import TCLconfigs
import boto3
# JWT stuff
# TODO: find a way to include native cryptography library
# Need to include cryptography wheels in the Lambda layer
# Right now I am just falling back to python library (slow)
import jwt
import requests
from TCLconfigs.logger import Logger
from jwt.contrib.algorithms.py_ecdsa import ECAlgorithm

# The public key corresponding to the private key used to encode the token
PUBLIC_KEY = TCLconfigs.public_key

jwt.unregister_algorithm('ES256')
jwt.register_algorithm('ES256', ECAlgorithm(ECAlgorithm.SHA256))
# Configure logger
logger = Logger().get_logger()
# dynamodb
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(TCLconfigs.dynamo_table_names('user_info'))


# def build_iam_policy(principal_id, effect, resource, context):
#     """
#     构建权限策略
#     :param principal_id: 这里使用ssoId
#     :param effect: Allow or Deny
#     :param resource: 需要访问的函数资源 methodArn
#     :param context: 传递到下一个函数的数据(ssoId、lang、appId、expired)
#     """
예제 #12
0
import urllib
import datetime

import jwt
try:
    from jwt.contrib.algorithms.py_ecdsa import ECAlgorithm
    jwt.register_algorithm('ES256', ECAlgorithm(
        ECAlgorithm.SHA256))  # Legacy encryption for Google app Engine
except BaseException:
    pass  # Cpython supported by this system

from models import Secret


class JWTError(Exception):
    pass


def get_token_from_header(headers):
    auth = headers.get('Authorization', '')
    try:
        standard, token = auth.split(' ')
    except:
        standard = token = None
    if standard != 'Bearer':
        raise JWTError('Authorization header must be "Bearer {Token}"')
    return token


def verify_jwt(headers):
    token = get_token_from_header(headers)
예제 #13
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')
예제 #14
0
A number of example token claims are provided.  These have been
generated directly by iam-services, so they should be assumed accurate.

They have been altered to extend the expiration.

Requirements:
    pip install crypto, PyJWT

"""

import Crypto
import jwt

from jwt.contrib.algorithms.pycrypto import RSAAlgorithm

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


#####################
# Keypair information
#####################

key_tuple = (
    long(24817274073206754688089592776519460949993444832444465314388162966279215222541242370345932006647969582133527832561571271768246177219593612597946389077957724223941590730268297872983736606496903131842239263202422685928604632113817403094928625050040388835058652109541294151564277666894800286197651304640441484131394293710877245812362804237018108331192362259905398454481188527795648400306295307416517142699592543985768442044996504164192500503843801666313632884910727025952779596604561869859910499774223571385622645368847832384519343364333564714339411497698156134852802082548052571415951864868489908018458922239880432536529),
    long(65537),
    long(18287010384108222796240636806135126847385193674541222804864933792629443848924449952679337602652604590695215314861275307936465575023095575622625799492694728446871039253339588947955057573598859362542158147284303467489573445443649694527675864945245440859707530519766974032490686132866681346736301277197555581605170595036508102440564807104557131459961525911328285283603815143800043553563200255989274923615935513052726663259861627594846950626573304436443806425545339373239680499037435170324729887098111542701548398800384779491496310747939430367315930866794439750262909660507211527701974062977118068431713762640280196910417)
)


#############
# Helper data
예제 #15
0
import os, sys, logging

from flask import Flask, render_template, request, jsonify, g
from functools import wraps
from datetime import datetime, timedelta

import json

import jwt
from jwt.contrib.algorithms.pycrypto import RSAAlgorithm
from jwt.exceptions import DecodeError, ExpiredSignature

jwt_algorithm = 'RS256'
token_timeout = 5 # minutes

jwt.register_algorithm(jwt_algorithm, RSAAlgorithm(RSAAlgorithm.SHA256))

app = Flask(__name__)
app.logger.addHandler(logging.StreamHandler(stream=sys.stderr))

APP_ROOT = os.path.dirname(os.path.abspath(__file__))   # refers to application_top

pvtkey_filepath = os.path.join(APP_ROOT, 'private.key')

try:
	# you may not commit private_key.pem
	app.config['SECRET_KEY'] = open(pvtkey_filepath, 'rb').read()
except:
	logging.error('Could not read private key.')

예제 #16
0
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)