Skip to content

Commit 00a574b

Browse files
Merge branch 'dev_quickstart' into 'master'
Initial pass to implement the Approov Quickstart with the Django framework. See merge request criticalblue/playground/quickstart-python-django-token-check!1
2 parents 2bde591 + 3ac6bfd commit 00a574b

36 files changed

+1623
-0
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,4 @@
11
.env
2+
venv/
3+
db.sqlite3
4+
__pycache__

README.md

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,111 @@
55
This repo implements the Approov server-side request verification code in Python, which performs the verification check before allowing valid traffic to be processed by the API endpoint.
66

77
This is an Approov integration quickstart example for the Python Django framework. If you are looking for another Python integration you can check our list of [quickstarts](https://approov.io/docs/latest/approov-integration-examples/backend-api/), and if you don't find what you are looking for, then please let us know [here](https://approov.io/contact). Meanwhile, you can always use the framework agnostic [quickstart example](https://github.com/approov/quickstart-python-token-check) for Python, and you may find that's easily adaptable to your framework of choice.
8+
9+
10+
## TOC - Table of Contents
11+
12+
* [Why?](#why)
13+
* [How it Works?](#how-it-works)
14+
* [Quickstarts](#approov-integration-quickstarts)
15+
* [Examples](#approov-integration-examples)
16+
* [Useful Links](#useful-links)
17+
18+
19+
## Why?
20+
21+
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:
22+
23+
* Ensures that accesses to your API come from official versions of your apps; it blocks accesses from republished, modified, or tampered versions
24+
* Protects the sensitive data behind your API; it prevents direct API abuse from bots or scripts scraping data and other malicious activity
25+
* 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
26+
* Removes the need for an API key in the mobile app
27+
* 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.
28+
29+
[TOC](#toc---table-of-contents)
30+
31+
32+
## How it works?
33+
34+
This is a brief overview of how the Approov cloud service and the Python Django API 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.
35+
36+
### Approov Cloud Service
37+
38+
The Approov cloud service attests that a device is running a legitimate and tamper-free version of your mobile app.
39+
40+
* If the integrity check passes then a valid token is returned to the mobile app
41+
* If the integrity check fails then a legitimate looking token will be returned
42+
43+
In either case, the app, unaware of the token's validity, adds it to every request it makes to the Approov protected API(s).
44+
45+
### Python Django API Server
46+
47+
The Python Django API 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 Django API server.
48+
49+
The request is handled such that:
50+
51+
* If the Approov Token is valid, the request is allowed to be processed by the API endpoint
52+
* If the Approov Token is invalid, an HTTP 401 Unauthorized response is returned
53+
54+
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.
55+
56+
>#### System Clock
57+
>
58+
>In order to correctly check for the expiration times of the Approov tokens is very important that the Python Django API server is synchronizing automatically the system clock over the network with an authoritative time source. In Linux this is usually done with a NTP server.
59+
60+
[TOC](#toc---table-of-contents)
61+
62+
63+
## Approov Integration Quickstarts
64+
65+
The quickstart code for the Approov Python Django API 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)).
66+
* [Approov token check quickstart](/docs/APPROOV_TOKEN_QUICKSTART.md)
67+
* [Approov token check with token binding quickstart](/docs/APPROOV_TOKEN_BINDING_QUICKSTART.md)
68+
69+
Both the quickstarts are built from the unprotected example server defined in this Django [project](/src/unprotected-server/hello).
70+
71+
You can use Git to see the code differences between the two quickstarts:
72+
73+
```
74+
git diff --no-index src/approov-protected-server/token-check/hello/approov_middleware.py src/approov-protected-server/token-binding-check/hello/approov_middleware.py
75+
```
76+
77+
[TOC](#toc---table-of-contents)
78+
79+
80+
## Approov Integration Examples
81+
82+
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 Django API server.
83+
84+
### Testing with Postman
85+
86+
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 Django API server for testing. The collection contains requests with valid and invalid Approov tokens, and with and without token binding.
87+
88+
### Testing with Curl
89+
90+
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).
91+
92+
### The Dummy Secret
93+
94+
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==`.
95+
96+
[TOC](#toc---table-of-contents)
97+
98+
99+
## Useful Links
100+
101+
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:
102+
103+
* [Approov Free Trial](https://approov.io/signup)(no credit card needed)
104+
* [Approov QuickStarts](https://approov.io/docs/latest/approov-integration-examples/)
105+
* [Approov Live Demo](https://approov.io/product/demo)
106+
* [Approov Docs](https://approov.io/docs)
107+
* [Approov Blog](https://blog.approov.io)
108+
* [Approov Resources](https://approov.io/resource/)
109+
* [Approov Customer Stories](https://approov.io/customer)
110+
* [Approov Support](https://approov.zendesk.com/hc/en-gb/requests/new)
111+
* [About Us](https://approov.io/company)
112+
* [Contact Us](https://approov.io/contact)
113+
114+
115+
[TOC](#toc---table-of-contents)
Lines changed: 262 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,262 @@
1+
# Approov Token Binding Quickstart
2+
3+
This quickstart is for developers familiar with the Python Django framework 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 Django API server.
4+
5+
## TOC - Table of Contents
6+
7+
* [Why?](#why)
8+
* [How it Works?](#how-it-works)
9+
* [Requirements](#requirements)
10+
* [Approov Setup](#approov-setup)
11+
* [Approov Token Check](#approov-token-binding-check)
12+
* [Try the Approov Integration Example](#try-the-approov-integration-example)
13+
14+
15+
## Why?
16+
17+
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.
18+
19+
[TOC](#toc---table-of-contents)
20+
21+
22+
## How it works?
23+
24+
For more background, see the overview in the [README](/README.md#how-it-works) at the root of this repo.
25+
26+
The main functionality for the Approov token check is in the file [approov_middleware.py](/src/approov-protected-server/token-binding-check/hello/approov_middleware.py). Take a look at the `verifyApproovToken()` and `verifyApproovTokenBinding()` functions to see the simple code for the checks.
27+
28+
[TOC](#toc---table-of-contents)
29+
30+
31+
## Requirements
32+
33+
To complete this quickstart you will need both the Python and the Approov CLI tool installed.
34+
35+
* Python - Follow the official installation instructions from [here](https://wiki.python.org/moin/BeginnersGuide/Download)
36+
* Approov CLI - Follow our [installation instructions](https://approov.io/docs/latest/approov-installation/#approov-tool) and read more about each command and its options in the [documentation reference](https://approov.io/docs/latest/approov-cli-tool-reference/)
37+
38+
[TOC](#toc---table-of-contents)
39+
40+
41+
## Approov Setup
42+
43+
To use Approov with the Python Django API server we need a small amount of configuration. First, Approov needs to know the API domain that will be protected. Second, the Python Django API server needs the Approov Base64 encoded secret that will be used to verify the tokens generated by the Approov cloud service.
44+
45+
### Configure API Domain
46+
47+
Approov needs to know the domain name of the API for which it will issue tokens.
48+
49+
Add it with:
50+
51+
```text
52+
approov api -add your.api.domain.com
53+
```
54+
55+
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.
56+
57+
> **NOTE:** By default the pin is extracted from the public key of the leaf certificate served by the domain, as visible to the box executing the Approov CLI command and the Approov servers.
58+
59+
### Approov Secret
60+
61+
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 Django API server environment to check the signatures of the [Approov Tokens](https://www.approov.io/docs/latest/approov-usage-documentation/#approov-tokens) that it processes.
62+
63+
Retrieve the Approov secret with:
64+
65+
```text
66+
approov secret /path/to/approov/administration.tok -get base64
67+
```
68+
69+
> **NOTE:** The `approov secret` command requires an administration management token to execute successfully. Developer management tokens don't have sufficient privileges to get the secret.
70+
71+
#### Set the Approov Secret
72+
73+
Open the `.env` file and add the Approov secret to the var:
74+
75+
```text
76+
APPROOV_BASE64_SECRET=approov_base64_secret_here
77+
```
78+
79+
[TOC](#toc---table-of-contents)
80+
81+
82+
## Approov Token Check
83+
84+
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.
85+
86+
Add the [approov_middleware.py](/src/approov-protected-server/token-binding-check/hello/approov_middleware.py) class to your project:
87+
88+
```python
89+
from django.http import JsonResponse
90+
from os import getenv
91+
from dotenv import load_dotenv, find_dotenv
92+
import base64
93+
import jwt # https://github.com/jpadilla/pyjwt/
94+
import hashlib
95+
96+
# @link https://django.readthedocs.io/en/stable/topics/http/middleware.html
97+
class ApproovMiddleware:
98+
def __init__(self, get_response):
99+
self.get_response = get_response
100+
101+
load_dotenv(find_dotenv(), override=True)
102+
103+
# Token secret value obtained with the Approov CLI tool:
104+
# - approov secret <admin.tok> -get
105+
approov_base64_secret = getenv('APPROOV_BASE64_SECRET')
106+
107+
if approov_base64_secret == None:
108+
raise ValueError("Missing the value for environment variable: APPROOV_BASE64_SECRET")
109+
110+
self.APPROOV_SECRET = base64.b64decode(approov_base64_secret)
111+
112+
def __call__(self, request):
113+
approov_token_claims = self.verifyApproovToken(request)
114+
115+
if approov_token_claims == None:
116+
return JsonResponse({}, status = 401)
117+
118+
if self.verifyApproovTokenBinding(request, approov_token_claims) == False:
119+
return JsonResponse({}, status = 401)
120+
121+
return self.get_response(request)
122+
123+
# @link https://approov.io/docs/latest/approov-usage-documentation/#backend-integration
124+
def verifyApproovToken(self, request):
125+
approov_token = request.headers.get("Approov-Token")
126+
127+
# If we didn't find a token, then reject the request.
128+
if approov_token == None:
129+
# You may want to add some logging here.
130+
return None
131+
132+
try:
133+
# Decode the Approov token explicitly with the HS256 algorithm to avoid
134+
# the algorithm None attack.
135+
approov_token_claims = jwt.decode(approov_token, self.APPROOV_SECRET, algorithms=['HS256'])
136+
return approov_token_claims
137+
except jwt.ExpiredSignatureError as e:
138+
# You may want to add some logging here.
139+
return None
140+
except jwt.InvalidTokenError as e:
141+
# You may want to add some logging here.
142+
return None
143+
144+
# @link https://approov.io/docs/latest/approov-usage-documentation/#token-binding
145+
def verifyApproovTokenBinding(self, request, approov_token_claims):
146+
# Note that the `pay` claim will, under normal circumstances, be present,
147+
# but if the Approov failover system is enabled, then no claim will be
148+
# present, and in this case you want to return true, otherwise you will not
149+
# be able to benefit from the redundancy afforded by the failover system.
150+
if not 'pay' in approov_token_claims:
151+
# You may want to add some logging here.
152+
return True
153+
154+
# We use the Authorization token, but feel free to use another header in
155+
# the request. Beqar in mind that it needs to be the same header used in the
156+
# mobile app to qbind the request with the Approov token.
157+
token_binding_header = request.headers.get("Authorization")
158+
159+
if not token_binding_header:
160+
# You may want to add some logging here.
161+
return False
162+
163+
# We need to hash and base64 encode the token binding header, because that's
164+
# how it was included in the Approov token on the mobile app.
165+
token_binding_header_hash = hashlib.sha256(token_binding_header.encode('utf-8')).digest()
166+
token_binding_header_encoded = base64.b64encode(token_binding_header_hash).decode('utf-8')
167+
168+
if approov_token_claims['pay'] == token_binding_header_encoded:
169+
return True
170+
171+
return False
172+
```
173+
174+
Now, to activate the [Approov Middleware](/src/approov-protected-server/token-binding-check/hello/approov_middleware.py) you just need to include it in the middleware list of your [Django settings](/src/approov-protected-server/token-binding-check/hello/settings.py) as the first one in the list:
175+
176+
```python
177+
MIDDLEWARE = [
178+
'YOUR_APP_NAME.approov_middleware.ApproovMiddleware',
179+
'django.middleware.security.SecurityMiddleware',
180+
# lines omitted
181+
]
182+
```
183+
184+
> **NOTE:** The Approov middleware is included as the first one in the list because you don't want to waste your server resources in processing requests that don't have a valid Approov token. This approach will help your server to handle more load under a Denial of Service(DoS) attack.
185+
186+
A full working example for a simple Hello World server can be found at [src/approov-protected-server/token-check](/src/approov-protected-server/token-binding-check).
187+
188+
> **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`.
189+
190+
[TOC](#toc---table-of-contents)
191+
192+
193+
## Test your Approov Integration
194+
195+
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.
196+
197+
#### With Valid Approov Tokens
198+
199+
Generate a valid token example from the Approov Cloud service:
200+
201+
```
202+
approov token -setDataHashInToken 'Bearer authorizationtoken' -genExample your.api.domain.com
203+
```
204+
205+
Then make the request with the generated token:
206+
207+
```text
208+
curl -i --request GET 'https://your.api.domain.com/v1/shapes' \
209+
--header 'Authorization: Bearer authorizationtoken' \
210+
--header 'Approov-Token: APPROOV_TOKEN_EXAMPLE_HERE'
211+
```
212+
213+
The request should be accepted. For example:
214+
215+
```text
216+
HTTP/1.1 200 OK
217+
218+
...
219+
220+
{"message": "Hello, World!"}
221+
```
222+
223+
#### With Invalid Approov Tokens
224+
225+
##### No Authorization Token
226+
227+
Let's just remove the Authorization header from the request:
228+
229+
```text
230+
curl -i --request GET 'https://your.api.domain.com/v1/shapes' \
231+
--header 'Approov-Token: APPROOV_TOKEN_EXAMPLE_HERE'
232+
```
233+
234+
The above request should fail with an Unauthorized error. For example:
235+
236+
```text
237+
HTTP/1.1 401 Unauthorized
238+
239+
...
240+
241+
{}
242+
```
243+
244+
##### Same Approov Token with a Different Authorization Token
245+
246+
Make the request with the same generated token, but with another random authorization token:
247+
248+
```
249+
curl -i --request GET 'https://your.api.domain.com/v1/shapes' \
250+
--header 'Authorization: Bearer anotherauthorizationtoken' \
251+
--header 'Approov-Token: APPROOV_TOKEN_EXAMPLE_HERE'
252+
```
253+
254+
The above request should also fail with an Unauthorized error. For example:
255+
256+
```text
257+
HTTP/1.1 401 Unauthorized
258+
259+
...
260+
261+
{}
262+
```

0 commit comments

Comments
 (0)