REST APIs and Security in PHP

Disclaimer: I am not speaking with authority on this topic. I am simply recording my findings. This content is subject to change as I learn more.

I made a quick and dirty REST API at work today, after some whiteboarding with our lead developer. We're coming into this pretty fresh, only having consumed REST up to this point, so it's a learning experience for sure. One obvious consideration is security: is SSL with a key enough? Do we need more than one token per request, i.e. an application identifier and a private key? What about hashing/signing the request?

As it stands, we're requiring SSL, as well as two parameters: appid and appkey. The dual identifiers would allow us to grant varying levels of privileges to a given developer or host. SSL protects the security of these values, one of which (the key) is considered private.

Signing Requests

So, hopefully we're making the right assumptions so far. If SSL isn't enough, we may need to sign requests. This would protect keys against far-future replay attacks, as every request would expire after a short period. (Note that OAUTH 2.0 is dropping request signing in favor of a token, while emphasizing the importance of SSL.)

HMAC-SHA1 is one possible way to sign and verify a request using a shared secret that is not transferred over the wire. In this setup, we would transmit the public identifier (so the server can lookup the corresponding private key) and the HMAC digest. The signature is based on the HTTP method (e.g. GET), the current timestamp, and the path to the REST endpoint. This code allows for 60 seconds of drift (or network congestion) between the client and server clocks. Other comments are inline.

hmac-sig-client.php

[code name="hmac-sig-client.php"]

hmac-sig-server.php

[code name="hmac-sig-server.php"]

Resources