-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge branch 'dev_approov-quickstart' into 'master'
Approov Quickstarts See merge request criticalblue/playground/quickstart-python-fastapi-token-check!1
- Loading branch information
Showing
15 changed files
with
995 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
.env |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,264 @@ | ||
# Approov Token Binding Quickstart | ||
|
||
This quickstart is for developers familiar with Python who are looking for a quick intro into how they can add [Approov](https://approov.io) into an existing project. Therefore this will guide you through the necessary steps for adding Approov with token binding to an existing Python FastAPI server. | ||
|
||
## TOC - Table of Contents | ||
|
||
* [Why?](#why) | ||
* [How it Works?](#how-it-works) | ||
* [Requirements](#requirements) | ||
* [Approov Setup](#approov-setup) | ||
* [Approov Token Check](#approov-token-binding-check) | ||
* [Try the Approov Integration Example](#try-the-approov-integration-example) | ||
|
||
|
||
## Why? | ||
|
||
To lock down your API server to your mobile app. Please read the brief summary in the [README](/README.md#why) at the root of this repo or visit our [website](https://approov.io/product.html) for more details. | ||
|
||
[TOC](#toc---table-of-contents) | ||
|
||
|
||
## How it works? | ||
|
||
For more background, see the overview in the [README](/README.md#how-it-works) at the root of this repository. | ||
|
||
The main functionality for the Approov token binding check is in the file [src/approov-protected-server/token-binding-check/hello-server-protected.py](/src/approov-protected-server/token-binding-check/hello-server-protected.py). Take a look at the `verifyApproovToken()` and `verifyApproovTokenBinding()` functions to see the simple code for the checks. | ||
|
||
[TOC](#toc---table-of-contents) | ||
|
||
|
||
## Requirements | ||
|
||
To complete this quickstart you will need both the Python, FastAPI, and the Approov CLI tool installed. | ||
|
||
* [Python 3](https://wiki.python.org/moin/BeginnersGuide/Download) | ||
* [FastAPI](https://fastapi.tiangolo.com/tutorial/#install-fastapi) | ||
* [Approov CLI](https://approov.io/docs/latest/approov-installation/#approov-tool) - Learn how to use it [here](https://approov.io/docs/latest/approov-cli-tool-reference/) | ||
|
||
[TOC](#toc---table-of-contents) | ||
|
||
|
||
## Approov Setup | ||
|
||
To use Approov with the Python FastAPI server we need a small amount of configuration. First, Approov needs to know the API domain that will be protected. Second, the Python FastAPI server needs the Approov Base64 encoded secret that will be used to verify the tokens generated by the Approov cloud service. | ||
|
||
### Configure API Domain | ||
|
||
Approov needs to know the domain name of the API for which it will issue tokens. | ||
|
||
Add it with: | ||
|
||
```text | ||
approov api -add your.api.domain.com | ||
``` | ||
|
||
Adding the API domain also configures the [dynamic certificate pinning](https://approov.io/docs/latest/approov-usage-documentation/#approov-dynamic-pinning) setup, out of the box. | ||
|
||
> **NOTE:** By default the pin is extracted from the public key of the leaf certificate served by the domain, as visible to the box issuing the Approov CLI command and the Approov servers. | ||
### Approov Secret | ||
|
||
Approov tokens are signed with a symmetric secret. To verify tokens, we need to grab the secret using the [Approov secret command](https://approov.io/docs/latest/approov-cli-tool-reference/#secret-command) and plug it into the Python FastAPI server environment to check the signatures of the [Approov Tokens](https://www.approov.io/docs/latest/approov-usage-documentation/#approov-tokens) that it processes. | ||
|
||
Retrieve the Approov secret with: | ||
|
||
```text | ||
approov secret -get base64 | ||
``` | ||
|
||
> **NOTE:** The `approov secret` command requires an [administration role](https://approov.io/docs/latest/approov-usage-documentation/#account-access-roles) to execute successfully. | ||
#### Set the Approov Secret | ||
|
||
Open the `.env` file and add the Approov secret to the var: | ||
|
||
```text | ||
APPROOV_BASE64_SECRET=approov_base64_secret_here | ||
``` | ||
|
||
[TOC](#toc---table-of-contents) | ||
|
||
|
||
## Approov Token Check | ||
|
||
To check the Approov token we will use the [jpadilla/pyjwt/](https://github.com/jpadilla/pyjwt/) package, but you are free to use another one of your preference. | ||
|
||
Add this code to your project, just before your first API endpoint: | ||
|
||
```python | ||
from fastapi import FastAPI, Request | ||
from fastapi.responses import JSONResponse | ||
|
||
# @link https://github.com/jpadilla/pyjwt/ | ||
import jwt | ||
import base64 | ||
import hashlib | ||
|
||
# @link https://github.com/theskumar/python-dotenv | ||
from dotenv import load_dotenv, find_dotenv | ||
load_dotenv(find_dotenv(), override=True) | ||
from os import getenv | ||
|
||
# Token secret value obtained with the Approov CLI tool: | ||
# - approov secret -get | ||
approov_base64_secret = getenv('APPROOV_BASE64_SECRET') | ||
|
||
if approov_base64_secret == None: | ||
raise ValueError("Missing the value for environment variable: APPROOV_BASE64_SECRET") | ||
|
||
APPROOV_SECRET = base64.b64decode(approov_base64_secret) | ||
|
||
app = FastAPI() | ||
|
||
################################################################################ | ||
# ONLY ADD YOUR MIDDLEWARE BEFORE THIS LINE. | ||
# - FastAPI seems to execute middleware in the reverse we declare it in the | ||
# code. | ||
# - Approov middleware SHOULD be the first to be executed in the request life | ||
# cycle. | ||
################################################################################ | ||
|
||
# @link https://approov.io/docs/latest/approov-usage-documentation/#token-binding | ||
# @IMPORTANT FastAPI seems to execute middleware in the reverse order they | ||
# appear in the code, therefore this one must come right before the | ||
# verifyApproovToken() middleware. | ||
@app.middleware("http") | ||
async def verifyApproovTokenBinding(request: Request, call_next): | ||
# Note that the `pay` claim will, under normal circumstances, be present, | ||
# but if the Approov failover system is enabled, then no claim will be | ||
# present, and in this case you want to return true, otherwise you will not | ||
# be able to benefit from the redundancy afforded by the failover system. | ||
if not 'pay' in request.state.approov_token_claims: | ||
# You may want to add some logging here. | ||
return JSONResponse({}, status_code = 401) | ||
|
||
# We use the Authorization token, but feel free to use another header in | ||
# the request. Beqar in mind that it needs to be the same header used in the | ||
# mobile app to qbind the request with the Approov token. | ||
token_binding_header = request.headers.get("Authorization") | ||
|
||
if not token_binding_header: | ||
# You may want to add some logging here. | ||
return JSONResponse({}, status_code = 401) | ||
|
||
# We need to hash and base64 encode the token binding header, because that's | ||
# how it was included in the Approov token on the mobile app. | ||
token_binding_header_hash = hashlib.sha256(token_binding_header.encode('utf-8')).digest() | ||
token_binding_header_encoded = base64.b64encode(token_binding_header_hash).decode('utf-8') | ||
|
||
if request.state.approov_token_claims['pay'] == token_binding_header_encoded: | ||
return await call_next(request) | ||
|
||
return JSONResponse({}, status_code = 401) | ||
|
||
# @link https://approov.io/docs/latest/approov-usage-documentation/#backend-integration | ||
# @IMPORTANT FastAPI seems to execute middleware in the reverse order they | ||
# appear in the code, therefore this one must come as the LAST of the | ||
# middleware's. | ||
@app.middleware("http") | ||
async def verifyApproovToken(request: Request, call_next): | ||
approov_token = request.headers.get("Approov-Token") | ||
|
||
# If we didn't find a token, then reject the request. | ||
if approov_token == "": | ||
# You may want to add some logging here. | ||
# return None | ||
return JSONResponse({}, status_code = 401) | ||
|
||
try: | ||
# Decode the Approov token explicitly with the HS256 algorithm to avoid | ||
# the algorithm None attack. | ||
request.state.approov_token_claims = jwt.decode(approov_token, APPROOV_SECRET, algorithms=['HS256']) | ||
return await call_next(request) | ||
except jwt.ExpiredSignatureError as e: | ||
# You may want to add some logging here. | ||
return JSONResponse({}, status_code = 401) | ||
except jwt.InvalidTokenError as e: | ||
# You may want to add some logging here. | ||
return JSONResponse({}, status_code = 401) | ||
|
||
# @app.get("/") | ||
# async def root(): | ||
# return {"message": "Hello World"} | ||
``` | ||
|
||
> **NOTE:** When the Approov token validation fails we return a `401` with an empty body, because we don't want to give clues to an attacker about the reason the request failed, and you can go even further by returning a `400`. | ||
Using the middleware approach will ensure that all endpoints in your API will be protected by Approov. | ||
|
||
A full working example for a simple Hello World server can be found at [src/approov-protected-server/token-binding-check](/src/approov-protected-server/token-binding-check). | ||
|
||
[TOC](#toc---table-of-contents) | ||
|
||
|
||
## Test your Approov Integration | ||
|
||
The following examples below use cURL, but you can also use the [Postman Collection](/README.md#testing-with-postman) to make the API requests. Just remember that you need to adjust the urls and tokens defined in the collection to match your deployment. Alternatively, the above README also contains instructions for using the preset _dummy_ secret to test your Approov integration. | ||
|
||
#### With Valid Approov Tokens | ||
|
||
Generate a valid token example from the Approov Cloud service: | ||
|
||
``` | ||
approov token -setDataHashInToken 'Bearer authorizationtoken' -genExample your.api.domain.com | ||
``` | ||
|
||
Then make the request with the generated token: | ||
|
||
```text | ||
curl -i --request GET 'https://your.api.domain.com/v1/shapes' \ | ||
--header 'Authorization: Bearer authorizationtoken' \ | ||
--header 'Approov-Token: APPROOV_TOKEN_EXAMPLE_HERE' | ||
``` | ||
|
||
The request should be accepted. For example: | ||
|
||
```text | ||
HTTP/1.1 200 OK | ||
... | ||
{"message": "Hello, World!"} | ||
``` | ||
|
||
#### With Invalid Approov Tokens | ||
|
||
##### No Authorization Token | ||
|
||
Let's just remove the Authorization header from the request: | ||
|
||
```text | ||
curl -i --request GET 'https://your.api.domain.com/v1/shapes' \ | ||
--header 'Approov-Token: APPROOV_TOKEN_EXAMPLE_HERE' | ||
``` | ||
|
||
The above request should fail with an Unauthorized error. For example: | ||
|
||
```text | ||
HTTP/1.1 401 Unauthorized | ||
... | ||
{} | ||
``` | ||
|
||
##### Same Approov Token with a Different Authorization Token | ||
|
||
Make the request with the same generated token, but with another random authorization token: | ||
|
||
``` | ||
curl -i --request GET 'https://your.api.domain.com/v1/shapes' \ | ||
--header 'Authorization: Bearer anotherauthorizationtoken' \ | ||
--header 'Approov-Token: APPROOV_TOKEN_EXAMPLE_HERE' | ||
``` | ||
|
||
The above request should also fail with an Unauthorized error. For example: | ||
|
||
```text | ||
HTTP/1.1 401 Unauthorized | ||
... | ||
{} | ||
``` |
Oops, something went wrong.