Skip to content

Latest commit

 

History

History
323 lines (212 loc) · 12.2 KB

File metadata and controls

323 lines (212 loc) · 12.2 KB

Approov Token Binding Quickstart

This quickstart is for developers familiar with Swift 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 Swift 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 binding check is in the file ApproovTokenMiddleware.swift. 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 Swift with Vapor toolbox and the Approov CLI tool installed.

TOC

Approov Setup

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

Now, retrieve the Approov secret with:

approov secret -get base64

Set the Approov Secret

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

APPROOV_BASE64_SECRET=approov_base64_secret_here

TOC

Approov Token Check

To check the Approov token we will use the vapor/jwt and vapor/jwt-kit packages. The former is used to register the Approov middleware in the Vapor application while the later is used to perform the actual check.

Add the ApproovTokenMiddleware.swift to your Vapor project:

import Vapor

// Using JWTKit because the JWT package assumes the token has the prefix `Bearer`.
import JWTKit

struct ApproovJWTPayload: JWTPayload {
    // Maps the longer Swift property names to the shortened keys used in the
    // JWT payload.
    enum CodingKeys: String, CodingKey {
        case expiration = "exp"
        case token_binding = "pay"
    }

    var expiration: ExpirationClaim

    var token_binding: String?

    // Run any additional verification logic beyond signature verification here.
    // Since we have an ExpirationClaim, we will call its verify method.
    func verify(using signer: JWTSigner) throws {
        try self.expiration.verifyNotExpired()
    }
}

final class ApproovTokenMiddleware: Middleware {
    public func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> {
        let approov_token_claims = verifyApproovToken(in: request)

        if approov_token_claims == nil {
            // You may want to add some logging here
            return request.eventLoop.makeFailedFuture(Abort(.unauthorized))
        }

        if !verifyApproovTokenBinding(in: request, claims: approov_token_claims) {
            // You may want to add some logging here
            return request.eventLoop.makeFailedFuture(Abort(.unauthorized))
        }

        return next.respond(to: request)
    }

    private func verifyApproovToken(in request: Request) -> ApproovJWTPayload? {
        if request.headers["Approov-Token"].isEmpty {
            // You may want to add some logging here
            return nil
        }

        let approov_token = request.headers["Approov-Token"][0]

        // Returns `nil` when the token signature is invalid or has expired.
        return try? request.application.jwt.signers.verify(approov_token, as: ApproovJWTPayload.self)
    }

    private func verifyApproovTokenBinding(in request: Request, claims approov_token_claims: ApproovJWTPayload?) -> Bool {
        if approov_token_claims!.token_binding == nil {
            // You may want to add some logging here
            return false
        }

        if request.headers["Authorization"].isEmpty {
            // You may want to add some logging here
            return false
        }

        let token_binding_header: String = request.headers["Authorization"][0]
        let hash_digest: SHA256Digest = SHA256.hash(data: Data(token_binding_header.utf8))
        let token_binding_header_encoded: String = Data(hash_digest).base64EncodedString()

        if approov_token_claims!.token_binding != token_binding_header_encoded {
            // You may want to add some logging here
            return false
        }

        return true
    }
}

Register it in the Vapor application configuration, in the file configure.swift:

import Vapor
import JWT

// configures your application
public func configure(_ app: Application) throws {
    // register the Approov middleware for all routes.
    try registerApproovMiddleware(app)

    // register routes
    try routes(app)
}

private func registerApproovMiddleware(_ app: Application) throws {
    let secret: String = Environment.get("APPROOV_BASE64_SECRET") ?? ""
    let approov_base64_secret: String = secret.trimmingCharacters(in: .whitespacesAndNewlines)

    if approov_base64_secret == "" {
        throw Abort(.internalServerError, reason: "Missing value for the environment variable APPROOV_BASE64_SECRET")
    }

    let approov_secret: Data? = Data(base64Encoded: approov_base64_secret)

    if approov_secret == nil {
        throw Abort(.internalServerError, reason: "The value in APPROOV_BASE64_SECRET env var is not a valid base64 encoded string.")
    }

    app.jwt.signers.use(.hs256(key: approov_secret!))
    app.middleware.use(ApproovTokenMiddleware())
}

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.

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

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 README at the root of this repo 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

...

{}

TOC

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