def parse(jwt): """Parse a JWT from a string.""" algorithm, payload, signature = jwt.split(".") signed_data = algorithm + "." + payload try: algorithm = decode_json_bytes(algorithm)["alg"] except KeyError: raise ValueError("badly formed JWT") payload = decode_json_bytes(payload) signature = decode_bytes(signature) return JWT(algorithm, payload, signature, signed_data)
def parse_jwt(data): """Parse a JWT from a string.""" header, payload, signature = data.split(".") signed_data = header + "." + payload try: header = decode_json_bytes(header) except KeyError: raise ValueError("badly formed JWT header") payload = decode_json_bytes(payload) signature = decode_bytes(signature) return ReceiptJWT(header, payload, signature, signed_data)
def main(): config = get_json(ISSUER + "/.well-known/fxa-client-configuration") if os.path.exists("./credentials.json"): with open("./credentials.json") as f: creds = json.loads(f.read()) print "Loaded credentials from ./credentials.json" else: creds = authenticate(config) with open("./credentials.json", "w") as f: f.write(json.dumps(creds, indent=4)) print "Saved credentials to ./credentials.json" access_token = creds["access_token"] sync_key = jwcrypto.jwk.JWK(**creds["keys"][SCOPE]) raw_sync_key = decode_bytes(sync_key.get_op_key('encrypt')) sync_key_bundle = KeyBundle( raw_sync_key[:32], raw_sync_key[32:], ) tokenserver_url = config["sync_tokenserver_base_url"] sync_creds = get_json(tokenserver_url + '/1.0/sync/1.5', headers={ 'Authorization': 'Bearer ' + access_token, 'X-KeyID': sync_key.key_id }) auth = HawkTokenAuth(b"0" * (3 * 32), "whatevz") auth.id = sync_creds["id"].encode('ascii') auth.auth_key = sync_creds["key"].encode('ascii') try: keys = get_json(sync_creds["api_endpoint"] + "/storage/crypto/keys", auth=auth) keys = decrypt_bso(sync_key_bundle, keys) default_key_bundle = KeyBundle( base64.b64decode(keys["default"][0]), base64.b64decode(keys["default"][1]), ) passwords = get_json(sync_creds["api_endpoint"] + "/storage/passwords?full=1", auth=auth) if not passwords: print "No synced passwords." else: passwords = [decrypt_bso(default_key_bundle, p) for p in passwords] passwords = [(p["id"], p["hostname"], p["username"], p["password"]) for p in passwords if not p.get("deleted", False)] print tabulate.tabulate( passwords, headers=["id", "hostname", "username", "password"], tablefmt="grid" ) except requests.exceptions.HTTPError as e: if e.response.status_code != 404: raise print "No synced passwords."
def post_browserid(request): """Get or create a token for this Assertion""" db = request.registry.browserid_db if 'assertion' in request.POST: # Persona login assertion = request.POST['assertion'] elif 'Authorization' in request.headers and \ request.headers['Authorization'].lower().startswith('browserid'): assertion = request.headers['Authorization'].split()[1] else: return forbidden_view() audience = json.loads(decode_bytes(assertion.split('.')[3]))['aud'] if audience not in request.registry['browserid.audiences']: raise HTTPBadRequest('Invalid audience') r = requests.post(request.registry['browserid.verifier_url'], data=json.dumps({'assertion': assertion, 'audience': audience}), headers={'Content-Type': 'application/json'}) if r.status_code == 500: raise HTTPBadRequest('An error occured: %s' % r.content) data = r.json() print data if data['issuer'] not in request.registry['browserid.trusted_issuers']: raise HTTPBadRequest( '%s is not configured as a trusted issuer.' % data['issuer'] ) user_id = data['email'] is_new = False try: token = db.get_user_token(user_id) except UserIdNotFound: is_new = True token = None token, credentials = get_hawk_credentials(token) if is_new: db.store_user_token(user_id, token) request.db.store_token(token, credentials) request.response.status = "201 Created" return { 'token': token, 'credentials': credentials }
def test_encode_decode_bytes(self): self.assertEquals("HELLO", decode_bytes(encode_bytes("HELLO"))) self.assertEquals("HELLO", decode_bytes(encode_bytes(u"HELLO"))) self.assertRaises(ValueError, decode_bytes, u"\N{SNOWMAN}") self.assertRaises(ValueError, decode_bytes, "A===")
def main(): arguments = docopt(HELP) host = arguments["--host"].rstrip('/') headers = {'content-type': 'application/json'} if arguments["--version"]: print("msisdn-cli %s" % __version__) sys.exit(0) verify = True if arguments["--insecure"]: verify = False # 1. Start the discover url = "%s/discover" % host discover_args = {"mcc": arguments["--mcc"], "roaming": False} if arguments["--mnc"] is not None: discover_args["mnc"] = arguments["--mnc"] if arguments["--msisdn"] is not None: discover_args["msisdn"] = arguments["--msisdn"] r = requests.post(url, json.dumps(discover_args), headers=headers, verify=verify) try: r.raise_for_status() except: print(url, r.content) raise discover = r.json() # 1.1 Register url = "%s/register" % host r = requests.post(url, headers=headers, verify=verify) try: r.raise_for_status() except: print(url, r.content) raise register = r.json() hawk_auth = HawkAuth(hawk_session=register["msisdnSessionToken"], server_url=host) hawkId = hawk_auth.credentials["id"] method = discover['verificationMethods'][0] try: mtSender = discover['verificationDetails'][method]["mtSender"] except KeyError: mtSender = '' # 2. If MT Flow if method == "sms/mt": # 2.1 If no MSISDN, ask the MSISDN if arguments["--msisdn"] is None: msisdn = input("Please enter your MSISDN number (ie +123456789): ") else: msisdn = arguments["--msisdn"] # 2.2 Start the registration print("MT Flow for %s" % msisdn) url = "%s/sms/mt/verify" % host verify_args = { "msisdn": msisdn, "mcc": discover_args["mcc"], "shortVerificationCode": True } r = requests.post(url, json.dumps(verify_args), auth=hawk_auth, headers=headers, verify=verify) try: r.raise_for_status() except: print(url, r.content) raise # 3. If MOMT Flow else: print("MOMT Flow") # 3.1 Give the Number and HawkId moVerifier = discover['verificationDetails']["sms/momt"]["moVerifier"] print("Please send the following message to %s:" % moVerifier) print("\n\tSMS %s\n" % hawkId.decode("ascii")) # 4. Ask for the code code = input("Please enter the code that you will get by SMS from %s: " % mtSender) # 5. Verify the code url = "%s/sms/verify_code" % host r = requests.post(url, json.dumps({"code": code.strip()}), auth=hawk_auth, headers=headers, verify=verify) try: r.raise_for_status() except: print(url, r.content) raise # 6. Print out the certificate publicKey, privateKey = get_keypair("msisdn") url = "%s/certificate/sign" % host sign_args = { "publicKey": json.dumps(publicKey), "duration": 86400 # One day } r = requests.post(url, json.dumps(sign_args), auth=hawk_auth, headers=headers, verify=verify) try: r.raise_for_status() except: print(url, r.content) raise sign = r.json() cert = sign["cert"] info = json.loads(decode_bytes(cert.split('.')[1]).decode("utf-8")) info["publicKey"] = "<stripped>" info["public-key"] = "<stripped>" info["pubkey"] = "<stripped>" print("Verified: %s" % json.dumps(info, indent=2, sort_keys=True)) # Build assertion if arguments["--audience"]: audience = arguments["--audience"] assertion = {"exp": int((time.time() + 60) * 1000), "aud": audience} assertion = bundle_certs_and_assertion([cert], jwt.generate( assertion, privateKey)) if arguments["--verbose"]: print("BID Assertion for %s:\n\n%s\n\n" % (audience, assertion)) if arguments["--dry-run"]: curl = """\ncurl -X POST -D - \\ -H 'Authorization: BROWSERID %s' \\""" % assertion if arguments["--data"]: curl += """ -d '%s' \\""" % arguments["--data"] if arguments["--json"]: curl += """ -H 'Content-Type: application/json' -H 'Accept: application/json' \\ -d '%s' \\""" % arguments["--json"] login_endpoint = arguments["--login-endpoint"] or "<login_URL>" curl += "\n %s\n" "" % login_endpoint print("\nTo validate the configuration of the service provider, " "you can run the curl command below.\n\n" "You should get a 200 OK status code with a " "Hawk-Session-Token header:\n\n") print(curl) print(ERROR_EXPLAINATION) else: headers = {"Authorization": "BROWSERID %s" % assertion} data = arguments["--data"] if arguments["--json"]: data = arguments["--json"] headers["Content-Type"] = "application/json" headers["Accept"] = "application/json" r = requests.post(arguments["--login-endpoint"], data=data, headers=headers, verify=verify) # Try to extract an Hawk sessionToken from the response. sessionToken = None if "Access-Control-Expose-Headers" in r.headers: tokenHeader = r.headers["Access-Control-Expose-Headers"] sessionHeaders = tokenHeader.split(",") sessionHeader = None for header in sessionHeaders: if "token" in header.lower(): sessionHeader = header.strip() break if sessionHeader: sessionToken = r.headers[sessionHeader] else: try: json_resp = r.json() for key in json_resp.keys(): if "token" in key.lower(): sessionToken = json_resp["key"] except ValueError: pass print("Status: %s" % r.status_code) if sessionToken: print("Hawk sessionToken: %s" % sessionToken) else: print("Headers: %s" % r.headers) print("Content: %s" % r.content)
def main(): arguments = docopt(HELP) host = arguments["--host"].rstrip('/') headers = {'content-type': 'application/json'} if arguments["--version"]: print("msisdn-cli %s" % __version__) sys.exit(0) verify = True if arguments["--insecure"]: verify = False # 1. Start the discover url = "%s/discover" % host discover_args = {"mcc": arguments["--mcc"], "roaming": False} if arguments["--mnc"] is not None: discover_args["mnc"] = arguments["--mnc"] if arguments["--msisdn"] is not None: discover_args["msisdn"] = arguments["--msisdn"] r = requests.post(url, json.dumps(discover_args), headers=headers, verify=verify) try: r.raise_for_status() except: print(url, r.content) raise discover = r.json() # 1.1 Register url = "%s/register" % host r = requests.post(url, headers=headers, verify=verify) try: r.raise_for_status() except: print(url, r.content) raise register = r.json() hawk_auth = HawkAuth(hawk_session=register["msisdnSessionToken"], server_url=host) hawkId = hawk_auth.credentials["id"] method = discover['verificationMethods'][0] try: mtSender = discover['verificationDetails'][method]["mtSender"] except KeyError: mtSender = '' # 2. If MT Flow if method == "sms/mt": # 2.1 If no MSISDN, ask the MSISDN if arguments["--msisdn"] is None: msisdn = input("Please enter your MSISDN number (ie +123456789): ") else: msisdn = arguments["--msisdn"] # 2.2 Start the registration print("MT Flow for %s" % msisdn) url = "%s/sms/mt/verify" % host verify_args = { "msisdn": msisdn, "mcc": discover_args["mcc"], "shortVerificationCode": True } r = requests.post(url, json.dumps(verify_args), auth=hawk_auth, headers=headers, verify=verify) try: r.raise_for_status() except: print(url, r.content) raise # 3. If MOMT Flow else: print("MOMT Flow") # 3.1 Give the Number and HawkId moVerifier = discover['verificationDetails']["sms/momt"]["moVerifier"] print("Please send the following message to %s:" % moVerifier) print("\n\tSMS %s\n" % hawkId.decode("ascii")) # 4. Ask for the code code = input( "Please enter the code that you will get by SMS from %s: " % mtSender ) # 5. Verify the code url = "%s/sms/verify_code" % host r = requests.post(url, json.dumps({"code": code.strip()}), auth=hawk_auth, headers=headers, verify=verify) try: r.raise_for_status() except: print(url, r.content) raise # 6. Print out the certificate publicKey, privateKey = get_keypair("msisdn") url = "%s/certificate/sign" % host sign_args = { "publicKey": json.dumps(publicKey), "duration": 86400 # One day } r = requests.post(url, json.dumps(sign_args), auth=hawk_auth, headers=headers, verify=verify) try: r.raise_for_status() except: print(url, r.content) raise sign = r.json() cert = sign["cert"] info = json.loads(decode_bytes(cert.split('.')[1]).decode("utf-8")) info["publicKey"] = "<stripped>" info["public-key"] = "<stripped>" info["pubkey"] = "<stripped>" print("Verified: %s" % json.dumps(info, indent=2, sort_keys=True)) # Build assertion if arguments["--audience"]: audience = arguments["--audience"] assertion = { "exp": int((time.time() + 60) * 1000), "aud": audience } assertion = bundle_certs_and_assertion( [cert], jwt.generate(assertion, privateKey) ) if arguments["--verbose"]: print("BID Assertion for %s:\n\n%s\n\n" % (audience, assertion)) if arguments["--dry-run"]: curl = """\ncurl -X POST -D - \\ -H 'Authorization: BROWSERID %s' \\""" % assertion if arguments["--data"]: curl += """ -d '%s' \\""" % arguments["--data"] if arguments["--json"]: curl += """ -H 'Content-Type: application/json' -H 'Accept: application/json' \\ -d '%s' \\""" % arguments["--json"] login_endpoint = arguments["--login-endpoint"] or "<login_URL>" curl += "\n %s\n""" % login_endpoint print("\nTo validate the configuration of the service provider, " "you can run the curl command below.\n\n" "You should get a 200 OK status code with a " "Hawk-Session-Token header:\n\n") print(curl) print(ERROR_EXPLAINATION) else: headers = {"Authorization": "BROWSERID %s" % assertion} data = arguments["--data"] if arguments["--json"]: data = arguments["--json"] headers["Content-Type"] = "application/json" headers["Accept"] = "application/json" r = requests.post(arguments["--login-endpoint"], data=data, headers=headers, verify=verify) # Try to extract an Hawk sessionToken from the response. sessionToken = None if "Access-Control-Expose-Headers" in r.headers: tokenHeader = r.headers["Access-Control-Expose-Headers"] sessionHeaders = tokenHeader.split(",") sessionHeader = None for header in sessionHeaders: if "token" in header.lower(): sessionHeader = header.strip() break if sessionHeader: sessionToken = r.headers[sessionHeader] else: try: json_resp = r.json() for key in json_resp.keys(): if "token" in key.lower(): sessionToken = json_resp["key"] except ValueError: pass print("Status: %s" % r.status_code) if sessionToken: print("Hawk sessionToken: %s" % sessionToken) else: print("Headers: %s" % r.headers) print("Content: %s" % r.content)