Skip to content

Latest commit

 

History

History
395 lines (277 loc) · 14.8 KB

APPROOV_TOKEN_BINDING_QUICKSTART.md

File metadata and controls

395 lines (277 loc) · 14.8 KB

Approov Token Binding Quickstart

This quickstart is for developers familiar with PHP Laravel framework who are looking for a quick intro into how they can add Approov into an existing project. Therefore this will guide you through the necessary steps for adding Approov with token binding to an existing PHP Laravel API server.

TOC - Table of Contents

Why?

To lock down your API server to your mobile app. Please read the brief summary in the Approov Overview at the root of this repo or visit our website for more details.

TOC

How it works?

For more background, see the Approov Overview at the root of this repository.

The main functionality for the Approov token check is in the Approov Middleware class. Take a look at the verifyApproovToken() and verifyApproovTokenBinding() functions to see the simple code for the checks.

TOC

Requirements

To complete this quickstart you will need both the PHP and the Approov CLI tool installed.

TOC

Approov Setup

To use Approov with the PHP Laravel API server we need a small amount of configuration. First, Approov needs to know the API domain that will be protected. Second, the PHP Laravel API 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:

approov api -add your.api.domain.com

NOTE: By default a symmetric key (HS256) is used to sign the Approov token on a valid attestation of the mobile app for each API domain it's added with the Approov CLI, so that all APIs will share the same secret and the backend needs to take care to keep this secret secure.

A more secure alternative is to use asymmetric keys (RS256 or others) that allows for a different keyset to be used on each API domain and for the Approov token to be verified with a public key that can only verify, but not sign, Approov tokens.

To implement the asymmetric key you need to change from using the symmetric HS256 algorithm to an asymmetric algorithm, for example RS256, that requires you to first add a new key, and then specify it when adding each API domain. Please visit Managing Key Sets on the Approov documentation for more details.

Adding the API domain also configures the dynamic certificate 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 executing 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 and plug it into the PHP Laravel API server environment to check the signatures of the Approov Tokens that it processes.

First, enable your Approov admin role with:

eval `approov role admin`

For the Windows powershell:

set APPROOV_ROLE=admin:___YOUR_APPROOV_ACCOUNT_NAME_HERE___

Next, retrieve the Approov secret with:

approov secret -get base64

@IMPORTANT: Don't set an Approov key id for the secret, because the JWT library doesn't support to pass the symmetric key for the Approov secret in a JWKs.

Set the Approov Secret

Open the .env file and add the Approov secret to the var:

APPROOV_BASE64_SECRET=approov_base64_secret_here

Now, let your Laravel app load it into the config, by creating a configuration file for Approov at config/approov.php:

<?php

return [
    'secret' => base64_decode(env('APPROOV_BASE64_SECRET'), true),
];

TOC

Approov Token Check

To check the Approov token we will use the firebase/php-jwt package, but you are free to use another one of your preference.

First, add the dependency to your project with:

composer require firebase/php-jwt

Next, add the Approov Middleware class to your project at app/Http/Middleware/Approov.php:

<?php declare(strict_types=1);

namespace App\Http\Middleware;

use Closure;
use Firebase\JWT\JWT;
use Symfony\Component\HttpFoundation\HeaderBag;

class Approov
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $approov_token_claims = $this->verifyApproovToken($request->headers);

        if (!$approov_token_claims) {
            return response()->json(new \stdClass(), 401);
        }

        if (!$this->verifyApproovTokenBinding($request->headers, $approov_token_claims)) {
            return response()->json(new \stdClass(), 401);
        }

        return $next($request);
    }

    /**
     * Verifies the Approov token in the incoming request.
     *
     * Returns the Approov token claims on success or null on failure.
     *
     * @param  Symfony\Component\HttpFoundation\HeaderBag  $headers
     * @return ?\stdClass
     */
    private function verifyApproovToken(HeaderBag $headers): ?\stdClass {
        try {
            $approov_token = $headers->get('Approov-Token');

            if (empty($approov_token)) {
                // You may want to add some logging here
                // \Log::debug("MISSING APPROOV TOKEN");
                return null;
            }

            $approov_secret = config('approov.secret');

            if (empty($approov_secret)) {
                // You may want to add some logging here
                // \Log::debug("MISSING APPROOV SECRET");
                return null;
            }

            // The Approov secret cannot be given as part of a JWKS key set,
            // therefore you cannot use the Approov CLI to set a key id for it.
            //
            // If you set the key id then the token check will fail due to the
            // presence of a `kid` key in the header of the Approov token, that
            // will not be found in the `$approov_secret` variable, because this
            // variable contains the secret as a binary string, not as a JWKs
            // key set.
            $approov_token_claims = JWT::decode($approov_token, $approov_secret, ['HS256']);
            return $approov_token_claims;

        } catch(\UnexpectedValueException $exception) {
            // You may want to add some logging here
            // \Log::debug($exception->getMessage());
            return null;
        } catch(\InvalidArgumentException $exception) {
            // You may want to add some logging here
            // \Log::debug($exception->getMessage());
            return null;
        } catch(\DomainException $exception) {
            // You may want to add some logging here
            // \Log::debug($exception->getMessage());
            return null;
        }

        // You may want to add some logging here
        return null;
    }

    /**
     * Verifies the Approov token binding for the Approov token in the incoming
     * request.
     *
     * The value in the `pay` claim of the Approov token must match the token
     * binding header being used, the `Authorization` header.
     *
     * @param  Symfony\Component\HttpFoundation\HeaderBag  $headers
     * @param  \stdClass  $approov_token_claims
     * @return bool
     */
    private function verifyApproovTokenBinding(HeaderBag $headers, \stdClass $approov_token_claims): bool {
        if (empty($approov_token_claims->pay)) {
            // You may want to add some logging here
            // \Log::debug("MISSING APPROOV TOKEN BINDING CLAIM");
            return false;
        }

        // We use the Authorization token, but feel free to use another header in
        // the request. Bear in mind that it needs to be the same header used in the
        // mobile app to bind the request with the Approov token.
        $token_binding_header = $headers->get('Authorization');

        if (empty($token_binding_header)) {
            // You may want to add some logging here
            // \Log::debug("MISSING APPROOV TOKEN BINDING HEADER");
            return false;
        }

        // 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_encoded = base64_encode(hash("sha256", $token_binding_header, true));

        if($approov_token_claims->pay !== $token_binding_header_encoded) {
            // You may want to add some logging here
            // \Log::debug("APPROOV TOKEN BINDING MISMATCH");
            return false;
        }

        return true;
    }
}

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.

Now, add the Approov Middleware to your Laravel application route middleware array at app/Http/Kernel.php:

protected $routeMiddleware = [
    'approov' => \App\Http\Middleware\Approov::class,
    'auth' => \App\Http\Middleware\Authenticate::class,
    // omitted lines for brevity
];

In the same file, you need to activate the Approov Middleware by including it as the first one in the array for the api route middleware group:

protected $middlewareGroups = [
    'web' => [
        // omitted lines for brevity
    ],

    'api' => [
        'approov',
        'throttle:60,1',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

NOTE: The Approov middleware is included as the first one in the array 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.

Adding the Approov Middleware class to the api middleware group means that any incoming request to an API route needs to have a valid Approov token with a matching token binding to be further processed. So, no need to explicitly add Approov as a middleware into any route in the file routes/api.php.

You can skip the Approov Middleware execution for any given route by using:

Route::get('/some-route', function () {
    // your code here
})->withoutMiddleware(['approov']);

A full working example for a simple Hello World server can be found at src/approov-protected-server/token-binding-check.

TOC

Test your Approov Integration

The following examples below use cURL, but you can also use the Postman Collection 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:

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:

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:

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:

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:

HTTP/1.1 401

...

{}

Issues

If you find any issue while following our instructions then just report it here, with the steps to reproduce it, and we will sort it out and/or guide you to the correct path.

TOC

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:

TOC