Skip to content

Commit

Permalink
Merge branch 'dev_approov-quickstart' into 'master'
Browse files Browse the repository at this point in the history
Approov Quickstarts

See merge request criticalblue/playground/quickstart-python-fastapi-token-check!1
  • Loading branch information
richardmtaylor committed Mar 5, 2021
2 parents 4222a59 + bcd1282 commit 5067deb
Show file tree
Hide file tree
Showing 15 changed files with 995 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.env
122 changes: 121 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,124 @@

[Approov](https://approov.io) is an API security solution used to verify that requests received by your backend services originate from trusted versions of your mobile apps.

This repo implements the Approov server-side request verification code in Python FastAPI framework, which performs the verification check before allowing valid traffic to be processed by the API endpoint.
This repo implements the Approov server-side request verification code with the Python FastAPI framework, which performs the verification check before allowing valid traffic to be processed by the API endpoint.


## TOC - Table of Contents

* [Why?](#why)
* [How it Works?](#how-it-works)
* [Quickstarts](#approov-integration-quickstarts)
* [Examples](#approov-integration-examples)
* [Useful Links](#useful-links)


## Why?

You can learn more about Approov, the motives for adopting it, and more detail on how it works by following this [link](https://approov.io/product). In brief, Approov:

* Ensures that accesses to your API come from official versions of your apps; it blocks accesses from republished, modified, or tampered versions
* Protects the sensitive data behind your API; it prevents direct API abuse from bots or scripts scraping data and other malicious activity
* Secures the communication channel between your app and your API with [Approov Dynamic Certificate Pinning](https://approov.io/docs/latest/approov-usage-documentation/#approov-dynamic-pinning). This has all the benefits of traditional pinning but without the drawbacks
* Removes the need for an API key in the mobile app
* Provides DoS protection against targeted attacks that aim to exhaust the API server resources to prevent real users from reaching the service or to at least degrade the user experience.

[TOC](#toc---table-of-contents)


## How it works?

This is a brief overview of how the Approov cloud service and the Python FastAPI server fit together from a backend perspective. For a complete overview of how the mobile app and backend fit together with the Approov cloud service and the Approov SDK we recommend to read the [Approov overview](https://approov.io/product) page on our website.

### Approov Cloud Service

The Approov cloud service attests that a device is running a legitimate and tamper-free version of your mobile app.

* If the integrity check passes then a valid token is returned to the mobile app
* If the integrity check fails then a legitimate looking token will be returned

In either case, the app, unaware of the token's validity, adds it to every request it makes to the Approov protected API(s).

### Python Backend Server

The Python FastAPI backend server ensures that the token supplied in the `Approov-Token` header is present and valid. The validation is done by using a shared secret known only to the Approov cloud service and the Python backend server.

The request is handled such that:

* If the Approov Token is valid, the request is allowed to be processed by the API endpoint
* If the Approov Token is invalid, an HTTP 401 Unauthorized response is returned

You can choose to log JWT verification failures, but we left it out on purpose so that you can have the choice of how you prefer to do it and decide the right amount of information you want to log.

>#### System Clock
>
>In order to correctly check for the expiration times of the Approov tokens is very important that the Python backend server is synchronizing automatically the system clock over the network with an authoritative time source. In Linux this is usual done with a NTP server.
[TOC](#toc---table-of-contents)


## Approov Integration Quickstarts

The quickstart code for the Approov Python server is split into two implementations. The first gets you up and running with basic token checking. The second uses a more advanced Approov feature, _token binding_. Token binding may be used to link the Approov token with other properties of the request, such as user authentication (more details can be found [here](https://approov.io/docs/latest/approov-usage-documentation/#token-binding)).
* [Approov token check quickstart](/docs/APPROOV_TOKEN_QUICKSTART.md)
* [Approov token check with token binding quickstart](/docs/APPROOV_TOKEN_BINDING_QUICKSTART.md)

Both the quickstarts are built from the unprotected example server defined [here](/src/unprotected-server/hello-server-unprotected.py), thus you can use Git to see the code differences between them.

Code difference between the Approov token check quickstart and the original unprotected server:

```
git diff --no-index src/unprotected-server/hello-server-unprotected.py src/approov-protected-server/token-check/hello-server-protected.py
```

You can do the same for the Approov token binding quickstart:

```
git diff --no-index src/unprotected-server/hello-server-unprotected.py src/approov-protected-server/token-binding-check/hello-server-protected.py
```

Or you can compare the code difference between the two quickstarts:

```
git diff --no-index src/approov-protected-server/token-check/hello-server-protected.py src/approov-protected-server/token-binding-check/hello-server-protected.py
```

[TOC](#toc---table-of-contents)


## Approov Integration Examples

The code examples for the Approov quickstarts are extracted from this simple [Approov integration examples](/src/approov-protected-server), that you can run from your computer to play around with the Approov integration and gain a better understanding of how simple and easy it is to integrate Approov in a Python API server.

### Testing with Postman

A ready-to-use Postman collection can be found [here](https://raw.githubusercontent.com/approov/postman-collections/master/quickstarts/hello-world/hello-world.postman_collection.json). It contains a comprehensive set of example requests to send to the Python server for testing. The collection contains requests with valid and invalid Approov tokens, and with and without token binding.

### Testing with Curl

An alternative to the Postman collection is to use cURL to make the API requests. Check some examples [here](https://github.com/approov/postman-collections/blob/master/quickstarts/hello-world/hello-world.postman_curl_requests_examples.md).

### The Dummy Secret

The valid Approov tokens in the Postman collection and cURL requests examples were signed with a dummy secret that was generated with `openssl rand -base64 64 | tr -d '\n'; echo`, therefore not a production secret retrieved with `approov secret -get base64`, thus in order to use it you need to set the `APPROOV_BASE64_SECRET`, in the `.env` file for each [Approov integration example](/src/approov-protected-server), to the following value: `h+CX0tOzdAAR9l15bWAqvq7w9olk66daIH+Xk+IAHhVVHszjDzeGobzNnqyRze3lw/WVyWrc2gZfh3XXfBOmww==`.

[TOC](#toc---table-of-contents)


## Useful Links

If you wish to explore the Approov solution in more depth, then why not try one of the following links as a jumping off point:

* [Approov Free Trial](https://approov.io/signup)(no credit card needed)
* [Approov QuickStarts](https://approov.io/docs/latest/approov-integration-examples/)
* [Approov Live Demo](https://approov.io/product/demo)
* [Approov Docs](https://approov.io/docs)
* [Approov Blog](https://blog.approov.io)
* [Approov Resources](https://approov.io/resource/)
* [Approov Customer Stories](https://approov.io/customer)
* [Approov Support](https://approov.zendesk.com/hc/en-gb/requests/new)
* [About Us](https://approov.io/company)
* [Contact Us](https://approov.io/contact)


[TOC](#toc---table-of-contents)
264 changes: 264 additions & 0 deletions docs/APPROOV_TOKEN_BINDING_QUICKSTART.md
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
...
{}
```
Loading

0 comments on commit 5067deb

Please sign in to comment.