Exemple #1
0
def decode_jwt(token):
    """
    Validate and decode the web token from the Amazon Cognito.
    Stores the public key needed to decrypt the token.
    Returns 
    """
    url="https://cognito-idp.{}.amazonaws.com/{}/.well-known/jwks.json".format(AWS_REGION,USER_POOL_ID)
    try:
        r = requests.get(url)
        logger.debug(r.status_code)
        key_set = load_jwks(r.text)
    except:
        logger.debug(traceback.format_exc())
        return False
    try:
        token_dict = jws.verify_compact(token, keys=key_set)
        logger.info(token_dict)
        if token_dict['exp'] < time.time():
            logger.debug("Token Expired")
            return False
        if token_dict['email_verified']:
            return {"user_id":token_dict['sub'], 
                    "user_email":token_dict['email']}
        else:
            logger.debug("E-mail not verfied.")
            return False
    except:
        logger.debug(traceback.format_exc())
        return False
Exemple #2
0
def gen_sym_key(ekid, new_kid=None, iv=None, k=None):
    out = {'kid': ekid, 'cty': 'b5+jwk+json'}

    if new_kid != None:
        kid = new_kid
    else:
        kid = gen_uuid()

    if k != None:
        new_key = k
    else:
        new_key = get_random_bytes(32)

    key_dat = {
        'alg': 'A256GCM',
        'ext': True,
        'key_ops': ['decrypt', 'encrypt'],
        'kty': 'oct',
        'kid': kid
    }

    key_dat['k'] = optestlib.opb64e(new_key)

    key_dat_str = json.dumps(key_dat)
    optestlib.p_str("New symmetric key", json.dumps(key_dat, indent=4))

    sym_keys[kid] = new_key
    if ekid == 'mp':
        #        sym_keys['mk'] = new_key

        optestlib.p_debug('\n*** Encrypting sym key with AES kid %s' % ekid)
        iv, ct = optestlib.enc_aes_gcm(key_dat_str, sym_keys[ekid], iv=iv)

        optestlib.p_data('IV', iv, dump=False)
        optestlib.p_data('KEY', sym_keys[ekid], dump=False)
        optestlib.p_data('Ciphertext', ct, dump=False)

        out['iv'] = optestlib.opb64e(iv)
        out['data'] = optestlib.opb64e(ct)
        out['enc'] = 'A256GCM'

    else:  # only the primary sym_key is itself AES encrypted, rest by RSA
        optestlib.p_debug('\n*** Encrypting sym key with RSA kid %s\n' % ekid)

        jwkj = '{"keys": [%s]}' % json.dumps(pub_keys[ekid])
        jwk = load_jwks(jwkj)[0]
        optestlib.p_str('Public key e:', jwk.e)
        optestlib.p_str('Public key n:', jwk.n)
        RSA_Key = RSA.construct((jwk.n, jwk.e))

        C = PKCS1_OAEP.new(RSA_Key)
        ct = C.encrypt(key_dat_str)

        out['enc'] = 'RSA-OAEP'
        out['data'] = optestlib.opb64e(ct)
        optestlib.p_debug('')
        optestlib.p_data('RSA-OAEP ciphertext', ct, dump=False)

    return kid, out
Exemple #3
0
 def store_key(self, access_token, tir):
     """
     Store key that was returned in response from token introspection
     :param access_token: The token that was introspected
     :param tir: TokenIntrospectionResponse instance
     """
     key = load_jwks(json.dumps({'keys': [json.loads(tir['key'])]}))
     self.token2key[access_token] = key
Exemple #4
0
 def store_key(self, access_token, tir):
     """
     Store key that was returned in response from token introspection
     :param access_token: The token that was introspected
     :param tir: TokenIntrospectionResponse instance
     """
     key = load_jwks(json.dumps({'keys': [json.loads(tir['key'])]}))
     self.token2key[access_token] = key
Exemple #5
0
def test_load_jwk():
    _ckey = x509_rsa_loads(open(CERT).read())
    jwk = dump_jwks([{"key": _ckey}])
    wk = load_jwks(jwk)
    print wk
    assert len(wk) == 1
    key = wk[0]
    assert key.kty == "RSA"
    assert isinstance(key.key, M2Crypto.RSA.RSA)
Exemple #6
0
def test_load_jwk():
    _ckey = pem_cert2rsa(CERT)
    jwk = dump_jwks([{"key": _ckey}])
    wk = load_jwks(jwk)
    print wk
    assert len(wk) == 1
    key = wk[0]
    assert key.kty == "RSA"
    assert isinstance(key.key, _RSAobj)
Exemple #7
0
def test_load_jwk():
    _ckey = pem_cert2rsa(CERT)
    jwk = dump_jwks([{"key": _ckey}])
    wk = load_jwks(jwk)
    print wk
    assert len(wk) == 1
    key = wk[0]
    assert key.kty == "RSA"
    assert isinstance(key.key, _RSAobj)
Exemple #8
0
    def _decode_token(self, token):
        """
        Checks for a valid signarute and decodes JWT signed LTI message

        This also touches the public keyset method.
        """
        public_keyset = self.key_handler.get_public_jwk()
        key_set = load_jwks(json.dumps(public_keyset))

        return JWS().verify_compact(token, keys=key_set)
    def _decode_token(self, token):
        """
        Checks for a valid signarute and decodes JWT signed LTI message

        This also tests the public keyset function.
        """
        public_keyset = self.lti_consumer.get_public_keyset()
        key_set = load_jwks(json.dumps(public_keyset))

        return JWS().verify_compact(token, keys=key_set)
Exemple #10
0
def test_loads_0():
    keys = load_jwks(json.dumps(JWK))
    assert len(keys) == 1
    key = keys[0]
    assert key.kid == "abc"
    assert key.kty == "RSA"

    _ckey = pem_cert2rsa(CERT)

    print key
    assert key.n == _ckey.n
    assert key.e == _ckey.e
Exemple #11
0
def test_loads_0():
    keys = load_jwks(json.dumps(JWK))
    assert len(keys) == 1
    key = keys[0]
    assert key.kid == "abc"
    assert key.kty == "RSA"

    _ckey = x509_rsa_loads(open(CERT).read())

    print key
    _n = long_to_mpi(base64_to_long(str(key.n)))
    assert _n == _ckey.n
    _e = long_to_mpi(base64_to_long(str(key.e)))
    assert _e == _ckey.e
Exemple #12
0
def test_loads_0():
    keys = load_jwks(json.dumps(JWK))
    assert len(keys) == 1
    key = keys[0]
    assert key.kid == "abc"
    assert key.kty == "RSA"

    _ckey = pem_cert2rsa(CERT)

    print key
    _n = base64_to_long(str(key.n))
    assert _n == _ckey.n
    _e = base64_to_long(str(key.e))
    assert _e == _ckey.e
Exemple #13
0
def test_loads_1():
    jwk = {
        "keys": [
            {
                'kty': 'RSA',
                'use': 'foo',
                'e': 'AQAB',
                "n": 'wf-wiusGhA-gleZYQAOPQlNUIucPiqXdPVyieDqQbXXOPBe3nuggtVzeq7pVFH1dZz4dY2Q2LA5DaegvP8kRvoSB_87ds3dy3Rfym_GUSc5B0l1TgEobcyaep8jguRoHto6GWHfCfKqoUYZq4N8vh4LLMQwLR6zi6Jtu82nB5k8',
                'kid': "1"
            }, {
                'kty': 'RSA',
                'use': 'bar',
                'e': 'AQAB',
                "n": 'wf-wiusGhA-gleZYQAOPQlNUIucPiqXdPVyieDqQbXXOPBe3nuggtVzeq7pVFH1dZz4dY2Q2LA5DaegvP8kRvoSB_87ds3dy3Rfym_GUSc5B0l1TgEobcyaep8jguRoHto6GWHfCfKqoUYZq4N8vh4LLMQwLR6zi6Jtu82nB5k8',
                'kid': "2"
            }
        ]
    }

    keys = load_jwks(json.dumps(jwk))
    print keys
    assert len(keys) == 2
    kids = [k.kid for k in keys]
    assert _eq(kids, ["1", "2"])
Exemple #14
0
def test_loads_1():
    JWK = {
        "keys": [
            {
                'kty': 'RSA',
                'use': 'foo',
                'e': 'AQAB',
                "n": 'wf-wiusGhA-gleZYQAOPQlNUIucPiqXdPVyieDqQbXXOPBe3nuggtVzeq7pVFH1dZz4dY2Q2LA5DaegvP8kRvoSB_87ds3dy3Rfym_GUSc5B0l1TgEobcyaep8jguRoHto6GWHfCfKqoUYZq4N8vh4LLMQwLR6zi6Jtu82nB5k8',
                'kid': "1"
            }, {
                'kty': 'RSA',
                'use': 'bar',
                'e': 'AQAB',
                "n": 'wf-wiusGhA-gleZYQAOPQlNUIucPiqXdPVyieDqQbXXOPBe3nuggtVzeq7pVFH1dZz4dY2Q2LA5DaegvP8kRvoSB_87ds3dy3Rfym_GUSc5B0l1TgEobcyaep8jguRoHto6GWHfCfKqoUYZq4N8vh4LLMQwLR6zi6Jtu82nB5k8',
                'kid': "2"
            }
        ]
    }

    keys = load_jwks(json.dumps(JWK))
    print keys
    assert len(keys) == 2
    kids = [k.kid for k in keys]
    assert _eq(kids, ["1", "2"])
Exemple #15
0
                        dest="jwk_url",
                        help="URL pointing to a file containing a JWK")
    parser.add_argument('-r',
                        dest="rsa_file",
                        help="A file containing a RSA key")
    parser.add_argument("-i", dest="int", help="Integrity method")
    parser.add_argument("-f", dest="file", help="File with the message")
    parser.add_argument("message", nargs="?", help="The message to encrypt")

    args = parser.parse_args()

    keys = {}
    if args.jwk_url:
        keys = assign(load_jwks_from_url(lrequest, args.jwk_url))
    elif args.jwk_file:
        keys = load_jwks(open(args.jwk_file).read())
    elif args.x509_url:
        keys = load_x509_cert(lrequest, args.x509_url)
    elif args.x509_file:
        keys = [import_rsa_key_from_file(args.x509_file)]
    elif args.rsa_file:
        key = rsa_load(args.rsa_file)
        rsa_key = RSAKey(key=key)
        rsa_key.serialize()
        keys = [rsa_key]
    else:
        print("Needs encryption key")
        exit()

    if args.file:
        msg = open(args.file).read()
Exemple #16
0
def test_load_jwks():
    keysl = load_jwks(json.dumps(JWKS))
    assert len(keysl) == 3
Exemple #17
0
    parser.add_argument('-a', dest="alg",
                        help="The encryption algorithm")
    parser.add_argument("-e", dest="enc", help="The encryption method")
    parser.add_argument("-m", dest="mode", default="public",
                        help="Whether a public or private key should be used")
    parser.add_argument("-f", dest="file",
                        help="File to be encrypted")
    parser.add_argument("message", nargs="?", help="The message to encrypt")

    args = parser.parse_args()

    keys = {}
    if args.jwk_url:
        keys = load_jwks_from_url(args.jwk_url, {})
    elif args.jwk_file:
        keys = load_jwks(open(args.jwk_file).read())
    elif args.x509_url:
        # load_x509_cert returns list of 2-tuples
        keys = [RSAKey(key=x) for x, y in load_x509_cert(lrequest,
                                                         args.x509_url)]
        for key in keys:
            key.serialize()
    elif args.x509_file:
        # import_rsa_key_from_file returns RSA key instance
        _key = RSAKey(key=import_rsa_key_from_file(args.x509_file))
        _key.serialize()
        keys = [_key]
    elif args.rsa_file:
        _key = RSAKey(key=rsa_load(args.rsa_file))
        _key.serialize()
        keys = [_key]
Exemple #18
0
import optestlib

#
# this ugly stuff is here because on some platforms (macOS), raw_input hangs
# after like 1024 bytes.
#
import termios, tty
old_tty_attr = termios.tcgetattr(sys.stdin)
new_tty_attr = old_tty_attr[:]
new_tty_attr[3] = new_tty_attr[3] & ~(tty.ICANON)
termios.tcsetattr(sys.stdin, tty.TCSANOW, new_tty_attr)

key_raw = raw_input("Enter RSA private key (as json, decrypted from keyset): ")

termios.tcsetattr(sys.stdin, tty.TCSANOW, old_tty_attr)

jwkj = '{"keys": [%s]}' % key_raw
jwk = json.loads(jwkj)

jwk = load_jwks(jwkj)[0]
RSA_Key = RSA.construct((jwk.n, jwk.e, jwk.d))

ct = optestlib.get_binary("\nEnter ciphertext (base-64 or hex): ")

cipher = PKCS1_OAEP.new(RSA_Key)
message = cipher.decrypt(ct)

print "\nDecrypted data:\n"
print message
Exemple #19
0
def test_load_jwks():
    keysl = load_jwks(json.dumps(JWKS))
    assert len(keysl) == 3
Exemple #20
0

    args = parser.parse_args()

    keys = []
    if args.rsa_file:
        keys = [RSAKey(key=import_rsa_key_from_file(args.rsa_file))]
    elif args.hmac_key:
        keys = [SYMKey(key=args.hmac_key)]

    if args.jwk:
        kspec = json.loads(open(args.jwk).read())
        keys.append(keyrep(kspec))

    if args.jwks:
        keys.extend(load_jwks(open(args.jwk).read()))

    if not keys:
        exit(-1)

    if args.msg_file:
        if args.msg_file == "A.2.1":
            message = open("A.2.1").read().replace("\n","\r\n")
        else:
            message = open(args.msg_file).read().strip("\n")
    elif args.message == "-":
        message = sys.stdin.read()
    else:
        message = args.message

    if args.sign:
Exemple #21
0
    parser.add_argument("-m", dest="mode", default="private",
                        help="Whether a public or private key should be used")
    parser.add_argument("-f", dest="file", help="File with the message")
    parser.add_argument("message", nargs="?", help="The message to encrypt")


    args = parser.parse_args()

    keys = {}
    if args.jwk_url:
        keys = assign(load_jwks_from_url(lrequest, args.jwk_url))
        if args.mode == "private":
            print >> sys.stderr, "Missing private key to decrypt with"
            exit()
    elif args.jwk_file:
        keys = assign(load_jwks(open(args.jwk_file).read()))
        if args.mode == "private":
            print >> sys.stderr, "Missing private key to decrypt with"
            exit()
    elif args.x509_url:
        keys = assign(load_x509_cert(lrequest, args.x509_url))
        if args.mode == "private":
            print >> sys.stderr, "Missing private key to decrypt with"
            exit()
    elif args.x509_file:
        keys = {"rsa": [x509_rsa_loads(open(args.x509_file).read())]}
        if args.mode == "private":
            print >> sys.stderr, "Missing private key to decrypt with"
            exit()
    elif args.rsa_file:
        keys = {"rsa": [rsa_load(args.rsa_file)]}