CloudServices/Sagrada/TokenServer: Difference between revisions

From MozillaWiki
Jump to navigation Jump to search
 
(8 intermediate revisions by 4 users not shown)
Line 1: Line 1:
= Goals =
= Goals =


So here's the challenge we face. Current login for sync looks like this:
tldr: having a centralized login service.


# provide username and password
See: http://docs.services.mozilla.com/token/index.html#goal-of-the-service
# we log into ldap with that username and password and grab your sync node
# we check the sync node against the url you've accessed, and use that to configure where your data is stored.


This solution works great for centralized login. It's fast, has a minimum number of steps, and caches the data centrally. The system that does node-assignment is lightweight, since the client and server both cache the result, and has support for multiple applications with the /node/<app> API protocol.
= APIS =


However, this breaks horribly when we don't have centralized login. And adding support for browserid to the SyncStorage protocol means that we're now there. We're going to get valid requests from users who don't have an account in LDAP. We won't even know, when they make a first request, if the node-assignment server has ever heard of them.
see http://docs.services.mozilla.com/token/apis.html


So, we have a bunch of requirements for the system. Not all of them are must-haves, but they're all things we need to think about trading off in whatever system gets designed:
* need to support multiple services (not necessarily centrally)
* need to be able to assign users to different machines as a service scales out, or somehow distribute them
* need to consistently send a user back to the same server once they've been assigned
* need to give operations some level of control over how users are allocated
* need to provide some recourse if a particular node dies
* need to handle exhaustion attacks. For example, I could set up an primary that just auto-approved any username, then loop through users until all nodes were full.
* need support for future developments like bucketed assignment
* Needs to be a system that scales infinitely.
= APIS v1.0 =
'''Unless stated otherwise, all APIs are using application/json for the requests and responses content types.'''
== GET /1.0/<app_name>/<app_version> ==
Asks for new token given some credentials in the Authorization header.
By default, the authentication scheme is Browser ID but other schemes can potentially be used if supported by the login server. '''app_name''' is the name of the application to access, like '''sync'''. '''app_version''' is the specific version number of the api that you want to access.
Example for Browser-Id:
 
<pre>
GET /1.0/sync/2.0
Host: token.services.mozilla.com
Authorization: Browser-ID <assertion>
</pre>
This API returns several values in a json mapping:
* '''oauth_consumer_key''' - a signed authorization token, containing the user's id and expiration
* '''oauth_consumer_secret''' - a secret derived from the shared secret
* '''service_entry''': a node url
Example:
<pre>
HTTP/1.1 200 OK
Content-Type: application/json
{'oauth_consumer_key': <token>,
'oauth_consumer_secret': <derived-secret>,
'service_entry': <node>,
}
</pre>
All errors are also returned as json responses, following the structure described in Cornice.
XXX need to document this in Cornice
Status codes and error codes:
* 404 : unknown URL (0), or unsupported application (1).
* 400 : malformed request - missing option or bad values(2) or malformed json (3) or unsupported authentication protocol (4)
* 401 : authentication failed or protocol not supported (5). The response in that case will contain WWW-Authenticate headers (one per supported scheme)
* 405 : unsupported method (6)
* 406 : unacceptable - the client asked for an Accept we don't support (7)
* 503 : service unavailable (ldap or snode backends may be down) (8)


= Proposed Design =
= Proposed Design =
Line 81: Line 21:
== Definitions and assumptions ==
== Definitions and assumptions ==


First, a few definitions.  The major players in the network topology are:
See http://docs.services.mozilla.com/token/index.html#assumptions
 
* '''Service''': a service Mozilla provides, like '''Sync''' or '''Easy Setup'''.
* '''Login Server''': used to authenticate user, returns tokens that can be used to authenticate to our services.
* '''Node''': an URL that identifies a service, like http://phx345
* '''Service Node''': a server that contains the service, and can be mapped to several Nodes (URLs)
* '''Node Assignment Server''': a service that can attribute to a user a node.
* '''User DB''': a database that keeps the user/node relation
* '''Cluster''': Group of webheads and storage devices that make up a set of Service Nodes.
* '''Colo''': physical datacenter, may contain multiple clusters
 
Cryptographically, we have the following terms:
 
* '''HKDF''':  HMAC-based Key Derivation Function, a method for deriving multiple secret keys from a single master secret (https://tools.ietf.org/html/rfc5869).
* '''Two-Legged OAuth''':  an authentication scheme for HTTP requests, based on a HMAC signature over the request metadata.  (http://tools.ietf.org/html/rfc5849#section-3)
* '''Auth Token''': used to identify the user after starting a session.  Contains the user application id and the expiration date.
* '''Master Secret''':  a secret shared between Login Server and Service Node. Never used directly, only for deriving other secrets.
* '''Signing Secret''': derived from the master secret, used to sign the auth token.
* '''Token Secret''':  derived from the master secret and auth token, used as '''oauth_consumer_secret'''. This is the only secret shared with the client and is different for each auth token.
 
Some assumptions:
 
* A Login Server detains the secret for all the Service Nodes for a given Service.
* Any given webhead in a cluster can receive calls to all service nodes in the cluster.
* The Login Server will support only BrowserID at first, but could support any authentication protocol in the future, as long as it can be done with a single call.
* All servers are time-synced
* The expires value for a token is a fixed value per application. For example it could be 30mn for Sync and 2 hours for bipostal.
* The Login Server keeps a white list of domains for BID verifications


== Flow ==
== Flow ==


Here's the proposed two-step flow (with Browser ID):
see http://docs.services.mozilla.com/token/user-flow.html
 
# the client trades a browser id assertion for an auth token and corresponding secret
# the client uses the auth token to sign subsequent requests using two-legged oauth
 
Getting an auth token:
 
<pre>
Client                      Login Server                  BID        User DB          Node Assignment Server 
===========================================================================================================
                                |                          |            |                    |               
request token ---- [1] --------->|------> verify --- [2] -->|            |                    |               
                                |      get node -- [3] ---|------------>|--> lookup          |               
                                |                          |            |<-- return node    |                 
                                |  attribute node --[4]----|-------------|------------------->|--> set node   
                                |                          |            |                    |<-- node       
                                |<--- build token  [5]    |            |                    |             
keep token <-------- [6] --------|                          |            |                    |               
</pre>
 
Calling the service:
 
<pre>
 
Client                                          Service Node
============================================================
create signed auth header [7]    |                | 
call node --------------- [8] ---|---------------->|--> verify token [9]
                                |                |    verify request signature [10]
                                |                |<-- process request [11]
get response <-------------------|-----------------|
</pre>
 
 
* the client requests a token, giving its browser id assertion [1]
 
    GET /1.0/sync/request_token HTTP/1.1
    Host: token.services.mozilla.com
    Authorization: Browser-ID <assertion>
   
* the Login Server checks the browser id assertion [2] '''this step will be done locally without calling an external browserid server -- but this could potentially happen''' (we can use pyvep + use the BID.org certificate)
* the Login Server asks the Users DB if the user is already allocated to a node. [3]
* if the user is not allocated to a node, the Login Server asks a new one to the Node Assignment Server [4]
* the Login Server creates a response with an auth token and corresponding token secret [5] and sends it back to the user.  The auth token contains the user id and a timestamp, and is signed using the signing secret.  The token secret is derived from the master secret and auth token using HKDF. It also adds the node url in the response under ''service_entry'' [6]
 
  HTTP/1.1 200 OK
  Content-Type: application/json
 
  {'oauth_consumer_key': <auth-token>,
    'oauth_consumer_secret': <token-secret>,
    'service_entry': <node>
    }
 
* the client saves the node location and oauth parameters to use in subsequent requests. [6]
* for each subsequent request to the Service, the client calculates a special Authorization header using two-legged OAuth [7] and sends the request to the allocated node location [8]
 
    POST /request HTTP/1.1
    Host: some.node.services.mozilla.com
    Authorization: OAuth realm="Example",
                    oauth_consumer_key=<auth-token> 
                    oauth_signature_method="HMAC-SHA1",
                    oauth_timestamp="137131201",  (client timestamp)
                    oauth_nonce="7d8f3e4a",
                    oauth_signature="bYT5CMsGcbgUdFHObYMEfcx6bsw%3D"
 
* the node uses the Signing Secret to validate the Auth Token [9].  If invalid or expired then the node returns a 401
* the node calculates the Token Secret from its Master Secret and the Auth Token, and checks whether the signature in the Authorization header is valid [10]. If it's an invalid then the node returns a 401
* the node processes the request as defined by the Service [11]


== Authorization token ==  
== Authorization token ==  
Line 188: Line 34:
* '''uid''': the app-specific user id (the user id integer in the case of sync)
* '''uid''': the app-specific user id (the user id integer in the case of sync)
* '''salt''': a randomly-generated salt for use in the calculation of the Token Secret (''optional'')
* '''salt''': a randomly-generated salt for use in the calculation of the Token Secret (''optional'')
* '''node''': the name of the service node to which the user is assigned


Example:
Example:


   auth_token = {"uid": 123, "expires": 1324654308.907832, "salt": "sghfwq6875765..UYgs"}   
   auth_token = {"uid": 123, "node": "https://sync-1.services.mozilla.com", "expires": 1324654308.907832, "salt": "sghfwq6875765..UYgs"}   


   
   
The token is signed using the Signing Secret and base64-ed. The signature is HMAC-SHA1:
The token is signed using the Signing Secret and base64-ed. The signature is HMAC-SHA256:


   auth_token, signature = HMAC-SHA1(auth_token, sig_secret)
   auth_token, signature = HMAC-SHA256(auth_token, sig_secret)
   auth_token = b64encode(auth_token, signature)
   auth_token = b64encode(auth_token, signature)


Line 203: Line 50:
== Secrets ==
== Secrets ==


Each Service Node has a unique Master Secret per Node it serves, it shares with the Login Server. A Master Secret is a timestamp rounded to the second, followed by a column, and a pseudo-random hex string of 256 chars from [a-f0-9].
Each Service Node has a unique Master Secret that it shares with the Login Server,which is used to sign and validate authentication tokens.  Multiple secrets can be active at any one time to support graceful rolling over to a new secret.
 
Example of generating such string:


  >>> import binascii, os, time
To simplify management of these secrets, the tokenserver maintains a single list of master secrets and derives a secret specific to each node using HKDF:
  >>> print '%d:%s' % (int(time.time()), binascii.b2a_hex(os.urandom(256))[:256])
  1326322983:646dc48...4ad86dca82d


(XXX crypto review required, not sure if this is the best/correct way to use HKDF for this purpose)
* node-info = "services.mozilla.com/mozsvc/v1/node_secret/" + node-name
* node-master-secret = HKDF(master-secret, salt=None, info=node-info, size=digest-length)


The Master Secret is used to derive keys for various cryptographic routines.  At startup time, the Login Server and Node should pre-calculate and cache the signing key as follows:
The node-specific Master Secret is used to derive keys for various cryptographic routines.  At startup time, the Login Server and Node should pre-calculate and cache the signing key as follows:


* sig-secret:  HKDF(master-secret, salt=None, info="SIGNING", size=digest-length)
* sig-secret:  HKDF(node-master-secret, salt=None, info="SIGNING", size=digest-length)


By using a no salt (or a fixed salt) these secrets can be calculated once and then used for each request.
By using a no salt (or a fixed salt) these secrets can be calculated once and then used for each request.
Line 221: Line 65:
When issuing or checking an Auth Token, the corresponding Token Secret is calculated as:
When issuing or checking an Auth Token, the corresponding Token Secret is calculated as:


* token-secret:  b64encode(HKDF(master-secret, salt=token-salt, info=auth-token, size=digest-length))
* token-secret:  b64encode(HKDF(node-master-secret, salt=token-salt, info=auth-token, size=digest-length))


Note that the token-secret is base64-encoded for ease of transmission back to the client.
Note that the token-secret is base64-encoded for ease of transmission back to the client.




=== Shared Secrets File ===
=== Configuring Secrets ===
 
The tokenserver should be configured to use the DerivedSecrets class with the list of master secrets:
 
    [tokenserver]
    secrets.backend = mozsvc.secrets.DerivedSecrets
    secrets.master_secrets = master-secret-one master-secret-two
 
A suitable master secret can be generated using mozsvc as follows:


Ops create secrets for each Node, and maintain for each cluster a file containing all secrets. The file is deployed on the Login Server and on each Service Node. The Login Server has all clusters files.
    python -m mozsvc.secrets new


Each file is a CSV file called '''/var/moz/shared_secrets/CLUSTER''', where CLUSTER is the name of the cluster,
Each node should be configured to use the FixedSecrets class and its corresponding derived secret:


Example:
    [hawkauth]
    secrets.backend = mozsvc.secrets.FixedSecrets
    secrets.secrets = node-master-secret-one, node-master-secret-two
 
This prevents a compromise on one service node from leaking the secrets on all nodes.  A suitable node-specific secret can be derived from the master secret as follows:


     phx1,1326322983:secret
     python -m mozsvc.secrets derive <master_secret> https://<node_name>
    phx2,1326322990:secret
    ...




=== Secret Update Process ===
=== Secret Update Process ===


When an existing secret needs to be changed for whatever reason, Ops can add new secrets to the file.
To revoke the secrets for a specific node, simply rename it so that its derived secret will be different.
 
To update the master secrets, the following procedure should be used:
 
1) Generate the new master secret, but keep the old one as well for now
 
2) For each storage node, derive both the new and old node-specific secrets
and push them out, so that its config file looks like this:
 
    [hawkauth]
    secrets.backend = mozsvc.secrets.FixedSecrets
    secrets.secrets = <old-derived-node-secret-as-hex> <new-derived-node-secret-as-hex>
 
Restart it.  It is now able to accept tokens signed with either secret.


The new secret is appended to the Node's line on each file :
3) For each tokenserver webhead, update it with the new master secret, removing
the old one.  Its config file will look like:


    phx1,1326322983:secret,1326324523:secret
    [tokenserver]
    phx2,1326322990:secret
    secrets.backend = mozsvc.secrets.DerivedSecrets
    ...
    secrets.master_secrets = <new-master-secret-as-hex>


The Service Nodes are the first ones to be updated, then the Login Server is updated in turn, so the new tokens are immediatly recognized by the Nodes.  
Restart it.  It now generates tokens signed with the new derived secrets.


The Service Node sorts the secret by timestamp and tries the newest one, then fallback to the next one in case the token could not be validated.
4) Discard the old master secret.


The Login Server always works with the newest secret, so ignores older secrets when it creates tokens. Old secret are pruned eventually.
5) Wait for one token expiration period, e.g. five minutes.


The Login Server and Service Node applications should watch the files and reload them in case they change.
6) For each storage node, derive just the new node-specific secret and push
it out, so that its config file looks like this:


=== Pulling a secret ===
=== Pulling a secret ===

Latest revision as of 03:32, 12 June 2014

Goals

tldr: having a centralized login service.

See: http://docs.services.mozilla.com/token/index.html#goal-of-the-service

APIS

see http://docs.services.mozilla.com/token/apis.html


Proposed Design

This solution proposes to use a token-based authentication system. A user that wants to connect to one of our service asks to a central server an access token.

The central server, a.k.a. the Login Server checks the authenticity of the user with a supported authentication method, and attributes to the user a server he needs to use with that token.

The server, a.k.a. the Service Node, that gets called controls the validity of the token included in the request. Token have a limited lifespan.


Definitions and assumptions

See http://docs.services.mozilla.com/token/index.html#assumptions

Flow

see http://docs.services.mozilla.com/token/user-flow.html

Authorization token

A token is a json encoded mapping. The keys of the Authorization Token are:

  • expires: an expire timestamp (UTC) defaults to current time + 30 mn
  • uid: the app-specific user id (the user id integer in the case of sync)
  • salt: a randomly-generated salt for use in the calculation of the Token Secret (optional)
  • node: the name of the service node to which the user is assigned

Example:

 auth_token = {"uid": 123, "node": "https://sync-1.services.mozilla.com", "expires": 1324654308.907832, "salt": "sghfwq6875765..UYgs"}  


The token is signed using the Signing Secret and base64-ed. The signature is HMAC-SHA256:

 auth_token, signature = HMAC-SHA256(auth_token, sig_secret)
 auth_token = b64encode(auth_token, signature)

The authorization token is not encrypted

Secrets

Each Service Node has a unique Master Secret that it shares with the Login Server,which is used to sign and validate authentication tokens. Multiple secrets can be active at any one time to support graceful rolling over to a new secret.

To simplify management of these secrets, the tokenserver maintains a single list of master secrets and derives a secret specific to each node using HKDF:

  • node-info = "services.mozilla.com/mozsvc/v1/node_secret/" + node-name
  • node-master-secret = HKDF(master-secret, salt=None, info=node-info, size=digest-length)

The node-specific Master Secret is used to derive keys for various cryptographic routines. At startup time, the Login Server and Node should pre-calculate and cache the signing key as follows:

  • sig-secret: HKDF(node-master-secret, salt=None, info="SIGNING", size=digest-length)

By using a no salt (or a fixed salt) these secrets can be calculated once and then used for each request.

When issuing or checking an Auth Token, the corresponding Token Secret is calculated as:

  • token-secret: b64encode(HKDF(node-master-secret, salt=token-salt, info=auth-token, size=digest-length))

Note that the token-secret is base64-encoded for ease of transmission back to the client.


Configuring Secrets

The tokenserver should be configured to use the DerivedSecrets class with the list of master secrets:

   [tokenserver]
   secrets.backend = mozsvc.secrets.DerivedSecrets
   secrets.master_secrets = master-secret-one master-secret-two

A suitable master secret can be generated using mozsvc as follows:

   python -m mozsvc.secrets new

Each node should be configured to use the FixedSecrets class and its corresponding derived secret:

   [hawkauth]
   secrets.backend = mozsvc.secrets.FixedSecrets
   secrets.secrets = node-master-secret-one, node-master-secret-two

This prevents a compromise on one service node from leaking the secrets on all nodes. A suitable node-specific secret can be derived from the master secret as follows:

   python -m mozsvc.secrets derive <master_secret> https://<node_name>


Secret Update Process

To revoke the secrets for a specific node, simply rename it so that its derived secret will be different.

To update the master secrets, the following procedure should be used:

1) Generate the new master secret, but keep the old one as well for now

2) For each storage node, derive both the new and old node-specific secrets and push them out, so that its config file looks like this:

    [hawkauth]
    secrets.backend = mozsvc.secrets.FixedSecrets
    secrets.secrets = <old-derived-node-secret-as-hex> <new-derived-node-secret-as-hex>

Restart it. It is now able to accept tokens signed with either secret.

3) For each tokenserver webhead, update it with the new master secret, removing the old one. Its config file will look like:

    [tokenserver]
    secrets.backend = mozsvc.secrets.DerivedSecrets
    secrets.master_secrets = <new-master-secret-as-hex>

Restart it. It now generates tokens signed with the new derived secrets.

4) Discard the old master secret.

5) Wait for one token expiration period, e.g. five minutes.

6) For each storage node, derive just the new node-specific secret and push it out, so that its config file looks like this:

Pulling a secret

In case we want to instantly remove the validity of a secret, we add a new secret as described before, but prune the old secrets right away, so any token out there are instantly rejected.

Backward Compatibility

The Login server uses the same snode and ldap servers, so both authentication systems can cohabit during a transition period.

Infra/Scaling

On the Login Server

The flow is:

  1. the user ask for a token, with a browser id assertion
  2. the server verifies locally the assertion [CPU bound]
  3. the server calls the User DB [I/O Bound]
  4. the server calls the Node Assignment Server [I/O Bound] (optional)
  5. the server builds the token and sends it back [CPU bound]
  6. the user uses the node for the time of the ttl (30mn)

So, for 100k users it means we'll do 200k requests on the Login Server per hour, so 50 RPS. For 1M users, 500 RPS. For 10M users, 5000 RPS. For 100M users, 50000 RPS.


Deployment

  • A Login Server is stateless, so we can deploy as many as we want and have Zeus load balance over them
  • A Login Server sees all secrets, so it can be cross-cluster / cross-datacenter
  • The shared secrets files can stay in memory -- updating the files should ping the app so we reload them
  • The User DB is the current LDAP, and may evolve into a more specialised metadata DB later

On each Service Node

Flow :

  1. the server checks the token [CPU Bound]
  2. the server process the request [Sync = I/O Bound]


Phase 1

[End of January? Need to check with ally]

End to end prototype with low-level scaling

  • Fully defined API, including headers and errors
  • Assigns Nodes
  • Maintains Node state for a user (in the existing LDAP)
  • Issues valid tokens
  • Downs nodes if needed

Phase 2

[End of Q1?]

Scalable implementation of the above in place.

  • Migration
  • Operational support scripts (TBD)
  • Logging and Metrics


Implementation details

  • The Token Server web service is implemented using Cornice and Pyramid, and sends crypto work to a crypto service via zmq.
  • The Crypto worker is a c++ program using cryptopp


token.png