def _decrypt(self, request): """ Decrypt a JOSE encrypted request. :param request: Request to parse :type request: str :rtype: bool or jose.JWS """ jwe = jose.deserialize_compact(request.replace("\n", '')) decrypted = None decr_key = self._config.keys.private_key if not decr_key: self._logger.error("No asymmetric private key (named '_private') found in the keystore") return False self._logger.debug("Trying to decrypt request with key {!r}".format(decr_key)) try: decrypted = jose.decrypt(jwe, decr_key.jwk, expiry_seconds = decr_key.expiry_seconds) self._logger.debug("Decrypted {!r}".format(decrypted)) except jose.Expired as ex: self._logger.warning("Request encrypted with key {!r} has expired: {!r}".format(decr_key, ex)) except jose.Error as ex: self._logger.warning("Failed decrypt with key {!r}: {!r}".format(decr_key, ex)) raise EduIDAPIError('Could not decrypt request') if not 'v1' in decrypted.claims: self._logger.error("No 'v1' in decrypted claims: {!r}".format(decrypted)) return False to_verify = jose.deserialize_compact(decrypted.claims['v1']) #logger.debug("Decrypted claims to verify: {!r}".format(to_verify)) return to_verify
def test_jwe(self): bad_key = {'k': RSA.generate(2048).exportKey('PEM')} for (alg, jwk), enc in product(self.algs, self.encs): jwe = jose.encrypt(claims, rsa_pub_key, enc=enc, alg=alg) # make sure the body can't be loaded as json (should be encrypted) try: json.loads(jose.b64decode_url(jwe.ciphertext)) self.fail() except ValueError: pass token = jose.serialize_compact(jwe) jwt = jose.decrypt(jose.deserialize_compact(token), rsa_priv_key) self.assertNotIn(jose._TEMP_VER_KEY, claims) self.assertEqual(jwt.claims, claims) # invalid key try: jose.decrypt(jose.deserialize_compact(token), bad_key) self.fail() except jose.Error as e: self.assertEqual(e.message, 'Incorrect decryption.')
def test_jwe_direct_encryption(self): symmetric_key = "tisasymmetrickey" jwe = jose.encrypt(claims, "", alg = "dir",enc="A128CBC-HS256", dir_key = symmetric_key) # make sure the body can't be loaded as json (should be encrypted) try: json.loads(jose.b64decode_url(jwe.ciphertext)) self.fail() except ValueError: pass token = jose.serialize_compact(jwe) jwt = jose.decrypt(jose.deserialize_compact(token),"", dir_key = symmetric_key) self.assertNotIn(jose._TEMP_VER_KEY, claims) self.assertEqual(jwt.claims, claims) # invalid key badkey = "1234123412341234" try: jose.decrypt(jose.deserialize_compact(token), '', dir_key=badkey) self.fail() except jose.Error as e: self.assertEqual(e.message, 'Mismatched authentication tags')
def _decrypt_and_verify(self, plaintext, decr_key, signing_key, alg = 'RS256'): jwe = jose.deserialize_compact(plaintext.replace("\n", '')) decrypted = jose.decrypt(jwe, decr_key) if not 'v1' in decrypted.claims: return False to_verify = jose.deserialize_compact(decrypted.claims['v1']) jwt = jose.verify(to_verify, signing_key, alg=alg) return jwt
def test_serialize(self): invalid = '1.2.3.4' try: jose.deserialize_compact('1.2.3.4') self.fail() except ValueError as e: self.assertEqual(e.message, 'Malformed JWT')
def _decrypt_and_verify(self, plaintext, decr_key, signing_key, alg='RS256'): jwe = jose.deserialize_compact(plaintext.replace("\n", '')) decrypted = jose.decrypt(jwe, decr_key) if not 'v1' in decrypted.claims: return False to_verify = jose.deserialize_compact(decrypted.claims['v1']) jwt = jose.verify(to_verify, signing_key, alg=alg) return jwt
def test_jwe_ignores_expired_token_if_validate_claims_is_false(self): claims = {jose.CLAIM_EXPIRATION_TIME: int(time()) - 5} et = jose.serialize_compact( jose.spec_compliant_encrypt(claims, rsa_pub_key)) jose.spec_compliant_decrypt(jose.deserialize_compact(et), rsa_priv_key, validate_claims=False)
def test_jwe_decrypt_legacy_v1_without_temp_ver_incorrect_jwk(self): jwk_for_encrypt = {'k': PRIVATE_KEY} legacy_legacy_temp_ver = jose.serialize_compact( legacy_encrypt(claims, jwk_for_encrypt) ) jwk_for_decrypt = {'k': RSA.generate(2048).exportKey('PEM')} legacy_patch = mock.patch.object( jose, 'legacy_decrypt', wraps=jose.legacy_decrypt ) spec_patch = mock.patch.object( jose, 'spec_compliant_decrypt', wraps=jose.spec_compliant_decrypt ) with legacy_patch as legacy_mock, spec_patch as spec_mock: with self.assertRaises(jose.Error) as decryption_error: jose.decrypt( jose.deserialize_compact(legacy_legacy_temp_ver), jwk_for_decrypt) self.assertEqual(legacy_mock.call_count, 1) self.assertEqual(spec_mock.call_count, 1) self.assertEqual(decryption_error.exception.message, "Incorrect decryption.")
def test_jwe_decrypt_legacy_v1_without_temp_ver(self): jwk = {'k': PRIVATE_KEY} legacy_patch = mock.patch.object( jose, 'legacy_decrypt', wraps=jose.legacy_decrypt ) spec_patch = mock.patch.object( jose, 'spec_compliant_decrypt', wraps=jose.spec_compliant_decrypt ) legacy_legacy_temp_ver = jose.serialize_compact( legacy_encrypt(claims, jwk) ) with legacy_patch as legacy_mock, spec_patch as spec_mock: jwt = jose.decrypt( jose.deserialize_compact(legacy_legacy_temp_ver), jwk) self.assertEqual(legacy_mock.call_count, 1) self.assertEqual(spec_mock.call_count, 0) self.assertEqual(jwt.claims, claims) expected_header = { 'alg': 'RSA-OAEP', 'enc': 'A128CBC-HS256', } self.assertEqual(jwt.header, expected_header) self.assertNotIn('__v', jwt.header)
def test_jws_asym(self): algs = ('RS256', 'RS384', 'RS512') for alg in algs: st = jose.serialize_compact(jose.sign(claims, rsa_priv_key, alg=alg)) jwt = jose.verify(jose.deserialize_compact(st), rsa_pub_key) self.assertEqual(jwt.claims, claims)
def test_get_freja_state(self): user = self.app.central_userdb.get_user_by_eppn(self.test_user_eppn) proofing_state = create_proofing_state(user, self.test_user_nin) self.app.proofing_statedb.save(proofing_state) with self.session_cookie(self.browser, self.test_user_eppn) as browser: response = json.loads(browser.get('/freja/proofing').data) self.assertEqual(response['type'], 'GET_OIDC_PROOFING_FREJA_PROOFING_SUCCESS') jwk = {'k': self.app.config['FREJA_JWK_SECRET'].decode('hex')} jwt = str(response['payload']['iaRequestData']) request_data = jose.verify(jose.deserialize_compact(jwt), jwk, alg=self.app.config['FREJA_JWS_ALGORITHM']) expected = { 'iarp': 'TESTRP', 'opaque': '1' + json.dumps({ 'nonce': proofing_state.nonce, 'token': proofing_state.token }), 'proto': u'1.0' } self.assertIn('exp', request_data.claims) self.assertEqual(request_data.claims['iarp'], expected['iarp']) self.assertEqual(request_data.claims['opaque'], expected['opaque']) self.assertEqual(request_data.claims['proto'], expected['proto'])
def test_jwe_no_error_with_iat_claim(self): claims = {jose.CLAIM_ISSUED_AT: int(time()) - 15} et = jose.serialize_compact(jose.encrypt(claims, rsa_pub_key)) jose.decrypt(jose.deserialize_compact(et), rsa_priv_key, expiry_seconds=20)
def test_jwe(self): bad_key = {'k': RSA.generate(2048).exportKey('PEM')} jwe = legacy_encrypt(claims, rsa_pub_key) token = jose.serialize_compact(jwe) jwt = jose.decrypt(jose.deserialize_compact(token), rsa_priv_key) self.assertEqual(jwt.claims, claims) self.assertNotIn(jose._TEMP_VER_KEY, claims) # invalid key try: jose.decrypt(jose.deserialize_compact(token), bad_key) self.fail() except jose.Error as e: self.assertEqual(e.message, 'Incorrect decryption.')
def test_jwe_adata(self): adata = '42' for (alg, jwk), enc in product(self.algs, self.encs): et = jose.serialize_compact(jose.encrypt(claims, rsa_pub_key, adata=adata)) jwt = jose.legacy_decrypt(jose.deserialize_compact(et), rsa_priv_key, adata=adata) # make sure signatures don't match when adata isn't passed in try: hdr, dt = jose.legacy_decrypt(jose.deserialize_compact(et), rsa_priv_key) self.fail() except jose.Error as e: self.assertEqual(e.message, 'Mismatched authentication tags') self.assertEqual(jwt.claims, claims)
def test_jwe_adata(self): adata = '42' for (alg, jwk), enc in product(self.algs, self.encs): et = jose.serialize_compact(jose.encrypt(claims, rsa_pub_key, adata=adata)) jwt = jose.decrypt(jose.deserialize_compact(et), rsa_priv_key, adata=adata) # make sure signaures don't match when adata isn't passed in try: hdr, dt = jose.decrypt(jose.deserialize_compact(et), rsa_priv_key) self.fail() except jose.Error as e: self.assertEqual(e.message, 'Mismatched authentication tags') self.assertEqual(jwt.claims, claims)
def test_jws_sym(self): algs = ('HS256', 'HS384', 'HS512',) jwk = {'k': 'password'} for alg in algs: st = jose.serialize_compact(jose.sign(claims, jwk, alg=alg)) jwt = jose.verify(jose.deserialize_compact(st), jwk, alg) self.assertEqual(jwt.claims, claims)
def update(): resp={} content = request.data jwt = jose.decrypt(jose.deserialize_compact(content), priv_jwk) try: ipaddr = jwt[1]['ipaddr'] regid = jwt[1]['hostname'] except KeyError, e: return 'KeyError', 400
def test_jwe_add_header(self): add_header = {'foo': 'bar'} for (alg, jwk), enc in product(self.algs, self.encs): et = jose.serialize_compact( jose.encrypt(claims, rsa_pub_key, add_header=add_header)) jwt = jose.decrypt(jose.deserialize_compact(et), rsa_priv_key) self.assertEqual(jwt.header['foo'], add_header['foo'])
def test_jwe_add_header(self): add_header = {'foo': 'bar'} for (alg, jwk), enc in product(self.algs, self.encs): et = jose.serialize_compact(jose.encrypt(claims, rsa_pub_key, add_header=add_header)) jwt = jose.decrypt(jose.deserialize_compact(et), rsa_priv_key) self.assertEqual(jwt.header['foo'], add_header['foo'])
def test_version1(self): bad_key = {'k': RSA.generate(2048).exportKey('PEM')} jwe = legacy_encrypt(claims, rsa_pub_key, version=1) token = jose.serialize_compact(jwe) jwt = jose.decrypt(jose.deserialize_compact(token), rsa_priv_key) self.assertEqual(jwt.claims, claims) self.assertEqual(jwt.header.get(jose._TEMP_VER_KEY), 1)
def test_jwe_invalid_dates_error(self): claims = {'exp': time() - 5} et = jose.serialize_compact(jose.encrypt(claims, rsa_pub_key)) try: jose.decrypt(jose.deserialize_compact(et), rsa_priv_key) self.fail() # expecting expired token except ValueError: pass claims = {'nbf': time() + 5} et = jose.serialize_compact(jose.encrypt(claims, rsa_pub_key)) try: jose.decrypt(jose.deserialize_compact(et), rsa_priv_key) self.fail() # expecting not valid yet except ValueError: pass
def decrypt_response(self, ciphertext=None, return_jwt=False): """ Decrypt the response returned from send_request. :param ciphertext: Ciphertext to decrypt. If not supplied the last request response is used. :param return_jwt: Return the whole JOSE JWT or just the claims :type ciphertext: None | str | unicode :type return_jwt: bool :return: Decrypted result :rtype: dict | jose.JWT """ if ciphertext is None: ciphertext = self._request_result.text jwe = jose.deserialize_compact(ciphertext.replace("\n", '')) priv_key = self._config.keys.private_key if not priv_key.keytype == 'jose': raise EduIDAPIError("Non-jose private key unusuable with decrypt_response") decrypted = jose.decrypt(jwe, priv_key.jwk) if not 'v1' in decrypted.claims: self._logger.error("No 'v1' in decrypted claims: {!r}\n\n".format(decrypted)) raise EduIDAPIError("No 'v1' in decrypted claims") to_verify = jose.deserialize_compact(decrypted.claims['v1']) jwt = jose.verify(to_verify, self._api_key.jwk, alg = self._config.jose_alg) self._logger.debug("Good signature on response to request using key: {!r}".format( self._api_key.jwk )) if 'nonce' in self._claims: # there was a nonce in the request, verify it is also present in the response if not 'nonce' in jwt.claims: self._logger.warning("Nonce was present in request, but not in response:\n{!r}".format( jwt.claims )) raise EduIDAPIError("Request-Response nonce validation error") if jwt.claims['nonce'] != self._claims['nonce']: self._logger.warning("Response nonce {!r} does not match expected {!r}".format( jwt.claims['nonce'], self._claims['nonce'] )) if return_jwt: return jwt return jwt.claims
def test_jwe_expired_error_with_exp_claim(self): claims = {jose.CLAIM_EXPIRATION_TIME: int(time()) - 5} et = jose.serialize_compact(jose.encrypt(claims, rsa_pub_key)) try: jose.decrypt(jose.deserialize_compact(et), rsa_priv_key) self.fail() # expecting expired token except jose.Expired as e: pass self.assertEquals( e.args[0], 'Token expired at {}'.format( jose._format_timestamp(claims[jose.CLAIM_EXPIRATION_TIME])))
def test_jwe_not_yet_valid_error_with_nbf_claim(self): claims = {jose.CLAIM_NOT_BEFORE: int(time()) + 5} et = jose.serialize_compact(jose.encrypt(claims, rsa_pub_key)) try: jose.decrypt(jose.deserialize_compact(et), rsa_priv_key) self.fail() # expecting not valid yet except jose.NotYetValid as e: pass self.assertEquals( e.args[0], 'Token not valid until {}'.format( jose._format_timestamp(claims[jose.CLAIM_NOT_BEFORE])))
def getCert_v03(): #register with ddns logger.debug('Registering') resp={} content = request.data jwt = jose.decrypt(jose.deserialize_compact(content), priv_jwk) try: ipaddress = jwt[1]['ipaddr'] hostname = jwt[1]['hostname'] alg = jwt[1]['alg'] secret = jwt[1]['secret'] privkey = jwt[1]['privkey'] #to be used with LE except KeyError, e: return 'KeyError', 400
def decrypt_fluffy(jwe, key): print '\n*****************************' print 'Performing Decryption on ' + jwe print '*****************************' print "OPENING FILE" f = open(jwe, "r") data = f.read() f.close() os.remove(jwe) dec = jose.decrypt(jose.deserialize_compact(data), '', dir_key=key) out = json.dumps(dec, indent=4, separators=(', ', ': '), sort_keys=True) print out print '*****************************'
def test_jwe_not_yet_valid_error_with_nbf_claim(self): claims = {jose.CLAIM_NOT_BEFORE: int(time()) + 5} et = jose.serialize_compact(jose.encrypt(claims, rsa_pub_key)) try: jose.decrypt(jose.deserialize_compact(et), rsa_priv_key) self.fail() # expecting not valid yet except jose.NotYetValid as e: pass self.assertEquals( e.args[0], 'Token not valid until {}'.format( jose._format_timestamp(claims[jose.CLAIM_NOT_BEFORE]) ) )
def test_jwe_decrypt_legacy_v1(self): jwk = {'k': PRIVATE_KEY} legacy_patch = mock.patch.object(jose, 'legacy_decrypt', wraps=jose.legacy_decrypt) spec_patch = mock.patch.object(jose, 'spec_compliant_decrypt', wraps=jose.spec_compliant_decrypt) with legacy_patch as legacy_mock, spec_patch as spec_mock: jwt = jose.decrypt(jose.deserialize_compact(LEGACY_V1_TOKEN), jwk) self.assertEqual(legacy_mock.call_count, 1) self.assertEqual(spec_mock.call_count, 0) self.assertEqual(jwt.claims, claims) expected_header = {'alg': 'RSA-OAEP', 'enc': 'A128CBC-HS256', '__v': 1} self.assertEqual(jwt.header, expected_header)
def test_jwe_expired_error_with_exp_claim(self): claims = {jose.CLAIM_EXPIRATION_TIME: int(time()) - 5} et = jose.serialize_compact(jose.encrypt(claims, rsa_pub_key)) try: jose.decrypt(jose.deserialize_compact(et), rsa_priv_key) self.fail() # expecting expired token except jose.Expired as e: pass self.assertEquals( e.args[0], 'Token expired at {}'.format( jose._format_timestamp(claims[jose.CLAIM_EXPIRATION_TIME]) ) )
def test_jwe_expired_error_with_iat_claim(self): expiry_seconds = 10 claims = {jose.CLAIM_ISSUED_AT: int(time()) - 15} et = jose.serialize_compact(jose.encrypt(claims, rsa_pub_key)) try: jose.decrypt(jose.deserialize_compact(et), rsa_priv_key, expiry_seconds=expiry_seconds) self.fail() # expecting expired token except jose.Expired as e: pass expiration_time = claims[jose.CLAIM_ISSUED_AT] + expiry_seconds self.assertEquals( e.args[0], 'Token expired at {}'.format( jose._format_timestamp(expiration_time)))
def test_jwe_decrypt_compliant_incorrect_jwk(self): jwk_for_decrypt = {'k': RSA.generate(2048).exportKey('PEM')} legacy_patch = mock.patch.object(jose, 'legacy_decrypt', wraps=jose.legacy_decrypt) spec_patch = mock.patch.object(jose, 'spec_compliant_decrypt', wraps=jose.spec_compliant_decrypt) with legacy_patch as legacy_mock, spec_patch as spec_mock: with self.assertRaises(jose.Error) as decryption_error: jose.decrypt(jose.deserialize_compact(SPEC_COMPLIANT_TOKEN), jwk_for_decrypt) self.assertEqual(legacy_mock.call_count, 1) self.assertEqual(spec_mock.call_count, 1) self.assertEqual(decryption_error.exception.message, "Incorrect decryption.")
def test_jwe_compression(self): local_claims = copy(claims) for v in xrange(1000): local_claims['dummy_' + str(v)] = '0' * 100 jwe = jose.serialize_compact(jose.encrypt(local_claims, rsa_pub_key)) _, _, _, uncompressed_ciphertext, _ = jwe.split('.') jwe = jose.serialize_compact( jose.encrypt(local_claims, rsa_pub_key, compression='DEF')) _, _, _, compressed_ciphertext, _ = jwe.split('.') self.assertTrue( len(compressed_ciphertext) < len(uncompressed_ciphertext)) jwt = jose.decrypt(jose.deserialize_compact(jwe), rsa_priv_key) self.assertEqual(jwt.claims, local_claims)
def test_jwe_compression(self): local_claims = copy(claims) for v in xrange(1000): local_claims['dummy_' + str(v)] = '0' * 100 jwe = jose.serialize_compact(jose.encrypt(local_claims, rsa_pub_key)) _, _, _, uncompressed_ciphertext, _ = jwe.split('.') jwe = jose.serialize_compact(jose.encrypt(local_claims, rsa_pub_key, compression='DEF')) _, _, _, compressed_ciphertext, _ = jwe.split('.') self.assertTrue(len(compressed_ciphertext) < len(uncompressed_ciphertext)) jwt = jose.decrypt(jose.deserialize_compact(jwe), rsa_priv_key) self.assertEqual(jwt.claims, local_claims)
def test_jwe_decrypt_compliant_incorrect_jwk(self): jwk_for_decrypt = {'k': RSA.generate(2048).exportKey('PEM')} legacy_patch = mock.patch.object( jose, 'legacy_decrypt', wraps=jose.legacy_decrypt ) spec_patch = mock.patch.object( jose, 'spec_compliant_decrypt', wraps=jose.spec_compliant_decrypt ) with legacy_patch as legacy_mock, spec_patch as spec_mock: with self.assertRaises(jose.Error) as decryption_error: jose.decrypt( jose.deserialize_compact(SPEC_COMPLIANT_TOKEN), jwk_for_decrypt) self.assertEqual(legacy_mock.call_count, 1) self.assertEqual(spec_mock.call_count, 1) self.assertEqual(decryption_error.exception.message, "Incorrect decryption.")
def test_jwe_expired_error_with_iat_claim(self): expiry_seconds = 10 claims = {jose.CLAIM_ISSUED_AT: int(time()) - 15} et = jose.serialize_compact(jose.encrypt(claims, rsa_pub_key)) try: jose.decrypt(jose.deserialize_compact(et), rsa_priv_key, expiry_seconds=expiry_seconds) self.fail() # expecting expired token except jose.Expired as e: pass expiration_time = claims[jose.CLAIM_ISSUED_AT] + expiry_seconds self.assertEquals( e.args[0], 'Token expired at {}'.format( jose._format_timestamp(expiration_time) ) )
def test_jwe_decrypt_legacy_v1(self): jwk = {'k': PRIVATE_KEY} legacy_patch = mock.patch.object( jose, 'legacy_decrypt', wraps=jose.legacy_decrypt ) spec_patch = mock.patch.object( jose, 'spec_compliant_decrypt', wraps=jose.spec_compliant_decrypt ) with legacy_patch as legacy_mock, spec_patch as spec_mock: jwt = jose.decrypt(jose.deserialize_compact(LEGACY_V1_TOKEN), jwk) self.assertEqual(legacy_mock.call_count, 1) self.assertEqual(spec_mock.call_count, 0) self.assertEqual(jwt.claims, claims) expected_header = { 'alg': 'RSA-OAEP', 'enc': 'A128CBC-HS256', '__v': 1 } self.assertEqual(jwt.header, expected_header)
def lambda_handler(event, context): """AWS_LAMBDA:auth_gateway Validate the incoming token and produce the principal user identifier associated with the token. Decoding a JWT token inline. :param authorizationToken: Authentication token. :type authorizationToken: str. :param methodArn: Contains information on api_gateway_arn and aws_account_id. :type methodArn: str. :returns: AuthPolicy -- Policy object with access permissions. """ try: #retrieve claims from token jwt_token = jose.decrypt( jose.deserialize_compact(event['authorizationToken']), {'k': PRIVATE_KEY}) except jose.Error as jwt_exception: LOGGER.error(jwt_exception) raise Exception('Unauthorized') now_time = time.time() if now_time - 31104000 > jwt_token.claims['iat'] or\ jwt_token.claims['iss'] != 'medpass-aws' or\ jwt_token.claims['aud'] != 'webclient' or\ jwt_token.claims['type'] not in ['REGISTRATION', 'TEMPORARY', 'USER','PRE-MEDIC', 'MEDIC']: LOGGER.error('Tampered token (iss:' + jwt_token.claims['iss'] + ', aud:' + jwt_token.claims['aud'] + ', type:' + jwt_token.claims['type'] + ').') raise Exception('Unauthorized') #create policy tmp = event['methodArn'].split(':') api_gateway_arn_tmp = tmp[5].split('/') aws_account_id = tmp[4] LOGGER.info(jwt_token.claims['id']) principal_id = jwt_token.claims['id'] policy = AuthPolicy(principal_id, aws_account_id) #adjust policy to user profile if jwt_token.claims['type'] == 'MASTER': policy.allowMethod(HttpVerb.ALL, '/admin/user') if jwt_token.claims['type'] == 'ADMIN': policy.allowMethod(HttpVerb.ALL, '/admin/laboratory/user') policy.allowMethod(HttpVerb.ALL, '/admin/enterprise/user') if jwt_token.claims['type'] == 'REGISTRATION': policy.allowMethod(HttpVerb.POST, '/user') elif jwt_token.claims['type'] == 'TEMPORARY': policy.allowMethod(HttpVerb.OPTIONS, '/medic/temporary') policy.allowMethod(HttpVerb.GET, '/medic/temporary') elif jwt_token.claims['type'] == 'PRE-MEDIC': policy.allowMethod(HttpVerb.OPTIONS, '/medic') policy.allowMethod(HttpVerb.PUT, '/medic') elif jwt_token.claims['type'] == 'USER' or jwt_token.claims[ 'type'] == 'MEDIC': if jwt_token.claims['type'] == 'MEDIC': policy.allowMethod(HttpVerb.POST, '/medic') policy.allowMethod(HttpVerb.PUT, '/medic') policy.allowMethod(HttpVerb.OPTIONS, '/medic') policy.allowMethod(HttpVerb.GET, '/medic/patient') policy.allowMethod(HttpVerb.POST, '/medic/patient') policy.allowMethod(HttpVerb.OPTIONS, '/medic/patient') policy.allowMethod(HttpVerb.ALL, '/medic/calendar') policy.allowMethod(HttpVerb.GET, '/medic/dashboard') policy.allowMethod(HttpVerb.OPTIONS, '/medic/dashboard') policy.allowMethod(HttpVerb.GET, '/user') policy.allowMethod(HttpVerb.PUT, '/user') policy.allowMethod(HttpVerb.OPTIONS, '/user') policy.allowMethod(HttpVerb.POST, '/user/pendencies') policy.allowMethod(HttpVerb.OPTIONS, '/user/pendencies') policy.allowMethod(HttpVerb.POST, '/user/medics') policy.allowMethod(HttpVerb.OPTIONS, '/user/medics') policy.allowMethod(HttpVerb.ALL, '/user/goals') policy.allowMethod(HttpVerb.POST, '/question') policy.allowMethod(HttpVerb.OPTIONS, '/question') policy.allowMethod(HttpVerb.POST, '/question/risk') policy.allowMethod(HttpVerb.OPTIONS, '/question/risk') policy.allowMethod(HttpVerb.POST, '/question/index') policy.allowMethod(HttpVerb.OPTIONS, '/question/index') policy.allowMethod(HttpVerb.POST, '/question/assistance') policy.allowMethod(HttpVerb.OPTIONS, '/question/assistance') policy.allowMethod(HttpVerb.POST, '/question/historic') policy.allowMethod(HttpVerb.OPTIONS, '/question/historic') policy.allowMethod(HttpVerb.POST, '/registration') policy.allowMethod(HttpVerb.OPTIONS, '/registration') policy.allowMethod(HttpVerb.ALL, '/report') policy.allowMethod(HttpVerb.OPTIONS, '/report/pendencies') policy.allowMethod(HttpVerb.POST, '/report/pendencies') policy.allowMethod(HttpVerb.OPTIONS, '/report/risk') policy.allowMethod(HttpVerb.POST, '/report/risk') policy.allowMethod(HttpVerb.OPTIONS, '/report/share') policy.allowMethod(HttpVerb.POST, '/report/share') policy.allowMethod(HttpVerb.GET, '/report/share') policy.allowMethod(HttpVerb.DELETE, '/report/share') policy.allowMethod(HttpVerb.OPTIONS, '/dashboard') policy.allowMethod(HttpVerb.POST, '/dashboard') policy.allowMethod(HttpVerb.OPTIONS, '/forms') policy.allowMethod(HttpVerb.OPTIONS, '/forms/city') policy.allowMethod(HttpVerb.POST, '/forms/city') policy.allowMethod(HttpVerb.ALL, '/assistance') policy.allowMethod(HttpVerb.ALL, '/historic') policy.allowMethod(HttpVerb.ALL, '/web') policy.allowMethod(HttpVerb.OPTIONS, '/mail') policy.allowMethod(HttpVerb.OPTIONS, '/mail/faq') policy.allowMethod(HttpVerb.POST, '/mail/faq') policy.restApiId = api_gateway_arn_tmp[0] policy.region = tmp[3] policy.stage = api_gateway_arn_tmp[1] # Build the policy and exit the function using return output = policy.build() return output
# Send token print "\t< Send Token >" print "\t |" print "\t+-------+ +-------+" print "\t| | | |" print "\t| BA +----- INTERNET (bad guys) -----> MtB |" print "\t| | | |" print "\t+-------+ +-------+" print "\t |" print "\t< Receive Token >" print "\t |" # Verify Token using public key external print "\t< Verify token signature (token, public external key) >" print "\t |" try: signed_jws = jose.verify(jose.deserialize_compact(jwt), jwk, 'HS256') print "\t OK" print "\t |" except: print "\tWrong token signature! " print "\tError signing token! " e = sys.exc_info()[0] print "Error: %s" % e exit() print "\t< Decrypt information (information, MtB private key) >" print "\t |" try: # JWT(header={u'alg': u'HS256'}, claims={u'iss': u'http://www.example.com', u'sub': 42, u'exp': 1395674427}) header = signed_jws[0] claims = signed_jws[1]
# key = b"""-----BEGIN PRIVATE KEY----- # MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgsegINAr5xcE48BiD # yfXjsfQmEk1ReGtD7bSuKsKx04CgCgYIKoZIzj0DAQehRANCAASauMCp36D8FOF1 # 5OGI1+fe5oeRoCbY5yGQ2Jk0Gi9P92ksyvC8LK7JDqtzKfEf18UsScYc+NWffEtt # v413G73q # -----END PRIVATE KEY-----""" # k = {'k': 'password'} # # signed = jws.sign(data, k, algorithm='ES256') # print(signed) # data = jws.verify(signed, k, algorithms='ES256') # print(data) jwk = {'k': 'password'} jws = jose.sign(data, jwk, alg='HS256') # JWS(header='eyJhbGciOiAiSFMyNTYifQ', # payload='eyJpc3MiOiAiaHR0cDovL3d3dy5leGFtcGxlLmNvbSIsICJzdWIiOiA0MiwgImV4cCI6IDEzOTU2NzQ0Mjd9', # signature='WYApAiwiKd-eDClA1fg7XFrnfHzUTgrmdRQY4M19Vr8') # issue the compact serialized version to the clients. this is what will be # transported along with requests to target systems. jwt = jose.serialize_compact(jws) # 'eyJhbGciOiAiSFMyNTYifQ.eyJpc3MiOiAiaHR0cDovL3d3dy5leGFtcGxlLmNvbSIsICJzdWIiOiA0MiwgImV4cCI6IDEzOTU2NzQ0Mjd9.WYApAiwiKd-eDClA1fg7XFrnfHzUTgrmdRQY4M19Vr8' jose.verify(jose.deserialize_compact(jwt), jwk, 'HS256') # JWT(header={u'alg': u'HS256'}, claims={u'iss': u'http://www.example.com', u'sub': 42, u'exp': 1395674427})
def test_jwe_no_error_with_nbf_claim(self): claims = {jose.CLAIM_NOT_BEFORE: int(time()) - 5} et = jose.serialize_compact(jose.encrypt(claims, rsa_pub_key)) jose.decrypt(jose.deserialize_compact(et), rsa_priv_key)
def test_jwe_no_error_with_exp_claim(self): claims = {jose.CLAIM_EXPIRATION_TIME: int(time()) + 5} et = jose.serialize_compact(jose.encrypt(claims, rsa_pub_key)) jose.decrypt(jose.deserialize_compact(et), rsa_priv_key)
def test_jwe_ignores_expired_token_if_validate_claims_is_false(self): claims = {jose.CLAIM_EXPIRATION_TIME: int(time()) - 5} et = jose.serialize_compact(jose.encrypt(claims, rsa_pub_key)) jose.decrypt(jose.deserialize_compact(et), rsa_priv_key, validate_claims=False)