2 // vim: foldmethod=marker
4 /* Generic exception class
6 class OAuthException extends Exception {/*{{{*/
10 class OAuthConsumer {/*{{{*/
14 function __construct($key, $secret, $callback_url=NULL) {/*{{{*/
16 $this->secret = $secret;
17 $this->callback_url = $callback_url;
20 function __toString() {/*{{{*/
21 return "OAuthConsumer[key=$this->key,secret=$this->secret]";
25 class OAuthToken {/*{{{*/
26 // access tokens and request tokens
32 * secret = the token secret
34 function __construct($key, $secret) {/*{{{*/
36 $this->secret = $secret;
40 * generates the basic string serialization of a token that a server
41 * would respond to request_token and access_token calls with
43 function to_string() {/*{{{*/
44 return "oauth_token=" . OAuthUtil::urlencode_rfc3986($this->key) .
45 "&oauth_token_secret=" . OAuthUtil::urlencode_rfc3986($this->secret);
48 function __toString() {/*{{{*/
49 return $this->to_string();
53 class OAuthSignatureMethod {/*{{{*/
54 public function check_signature(&$request, $consumer, $token, $signature) {
55 $built = $this->build_signature($request, $consumer, $token);
56 return $built == $signature;
58 // Check for zero length, although unlikely here
59 if (strlen($built) == 0 || strlen($signature) == 0) {
63 if (strlen($built) != strlen($signature)) {
69 // Avoid a timing leak with a (hopefully) time insensitive compare
70 for ($i = 0; $i < strlen($signature); $i++) {
71 $result |= ord($built{$i}) ^ ord($signature{$i});
78 class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {/*{{{*/
79 function get_name() {/*{{{*/
83 public function build_signature($request, $consumer, $token) {/*{{{*/
84 $base_string = $request->get_signature_base_string();
85 $request->base_string = $base_string;
89 ($token) ? $token->secret : ""
92 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
93 $key = implode('&', $key_parts);
95 return base64_encode( hash_hmac('sha1', $base_string, $key, true));
99 class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {/*{{{*/
100 public function get_name() {/*{{{*/
104 public function build_signature($request, $consumer, $token) {/*{{{*/
106 OAuthUtil::urlencode_rfc3986($consumer->secret)
110 array_push($sig, OAuthUtil::urlencode_rfc3986($token->secret));
112 array_push($sig, '');
115 $raw = implode("&", $sig);
116 // for debug purposes
117 $request->base_string = $raw;
119 return OAuthUtil::urlencode_rfc3986($raw);
123 class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {/*{{{*/
124 public function get_name() {/*{{{*/
128 protected function fetch_public_cert(&$request) {/*{{{*/
129 // not implemented yet, ideas are:
130 // (1) do a lookup in a table of trusted certs keyed off of consumer
131 // (2) fetch via http using a url provided by the requester
132 // (3) some sort of specific discovery code based on request
134 // either way should return a string representation of the certificate
135 throw Exception("fetch_public_cert not implemented");
138 protected function fetch_private_cert(&$request) {/*{{{*/
139 // not implemented yet, ideas are:
140 // (1) do a lookup in a table of trusted certs keyed off of consumer
142 // either way should return a string representation of the certificate
143 throw Exception("fetch_private_cert not implemented");
146 public function build_signature(&$request, $consumer, $token) {/*{{{*/
147 $base_string = $request->get_signature_base_string();
148 $request->base_string = $base_string;
150 // Fetch the private key cert based on the request
151 $cert = $this->fetch_private_cert($request);
153 // Pull the private key ID from the certificate
154 $privatekeyid = openssl_get_privatekey($cert);
156 // Sign using the key
157 $ok = openssl_sign($base_string, $signature, $privatekeyid);
159 // Release the key resource
160 openssl_free_key($privatekeyid);
162 return base64_encode($signature);
165 public function check_signature(&$request, $consumer, $token, $signature) {/*{{{*/
166 $decoded_sig = base64_decode($signature);
168 $base_string = $request->get_signature_base_string();
170 // Fetch the public key cert based on the request
171 $cert = $this->fetch_public_cert($request);
173 // Pull the public key ID from the certificate
174 $publickeyid = openssl_get_publickey($cert);
176 // Check the computed signature against the one passed in the query
177 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
179 // Release the key resource
180 openssl_free_key($publickeyid);
186 class OAuthRequest {/*{{{*/
188 private $http_method;
190 // for debug purposes
192 public static $version = '1.0';
194 function __construct($http_method, $http_url, $parameters=NULL) {/*{{{*/
195 @$parameters or $parameters = array();
196 $this->parameters = $parameters;
197 $this->http_method = $http_method;
198 $this->http_url = $http_url;
203 * attempt to build up a request from what was passed to the server
205 public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {/*{{{*/
206 $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") ? 'http' : 'https';
207 @$http_url or $http_url = $scheme . '://' . $_SERVER['HTTP_HOST'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI'];
208 @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
210 $request_headers = OAuthRequest::get_headers();
212 // let the library user override things however they'd like, if they know
213 // which parameters to use then go for it, for example XMLRPC might want to
216 $req = new OAuthRequest($http_method, $http_url, $parameters);
218 // collect request parameters from query string (GET) and post-data (POST) if appropriate (note: POST vars have priority)
219 $req_parameters = $_GET;
220 if ($http_method == "POST" &&
221 ( @strstr($request_headers["Content-Type"], "application/x-www-form-urlencoded") || @strstr($_ENV["CONTENT_TYPE"], "application/x-www-form-urlencoded") )) {
222 $req_parameters = array_merge($req_parameters, $_POST);
225 // next check for the auth header, we need to do some extra stuff
226 // if that is the case, namely suck in the parameters from GET or POST
227 // so that we can include them in the signature
228 if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
229 $header_parameters = OAuthRequest::split_header($request_headers['Authorization']);
230 $parameters = array_merge($req_parameters, $header_parameters);
231 $req = new OAuthRequest($http_method, $http_url, $parameters);
232 } else $req = new OAuthRequest($http_method, $http_url, $req_parameters);
239 * pretty much a helper function to set up the request
241 public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {/*{{{*/
242 @$parameters or $parameters = array();
243 $defaults = array("oauth_version" => OAuthRequest::$version,
244 "oauth_nonce" => OAuthRequest::generate_nonce(),
245 "oauth_timestamp" => OAuthRequest::generate_timestamp(),
246 "oauth_consumer_key" => $consumer->key);
247 $parameters = array_merge($defaults, $parameters);
250 $parameters['oauth_token'] = $token->key;
252 return new OAuthRequest($http_method, $http_url, $parameters);
255 public function set_parameter($name, $value) {/*{{{*/
256 $this->parameters[$name] = $value;
259 public function get_parameter($name) {/*{{{*/
260 return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
263 public function get_parameters() {/*{{{*/
264 return $this->parameters;
268 * Returns the normalized parameters of the request
270 * This will be all (except oauth_signature) parameters,
271 * sorted first by key, and if duplicate keys, then by
274 * The returned string will be all the key=value pairs
279 public function get_signable_parameters() {/*{{{*/
280 // Grab all parameters
281 $params = $this->parameters;
283 // Remove oauth_signature if present
284 if (isset($params['oauth_signature'])) {
285 unset($params['oauth_signature']);
288 // Urlencode both keys and values
289 $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
290 $values = OAuthUtil::urlencode_rfc3986(array_values($params));
291 $params = array_combine($keys, $values);
293 // Sort by keys (natsort)
294 uksort($params, 'strcmp');
296 // Generate key=value pairs
298 foreach ($params as $key=>$value ) {
299 if (is_array($value)) {
300 // If the value is an array, it's because there are multiple
301 // with the same key, sort them, then add all the pairs
303 foreach ($value as $v2) {
304 $pairs[] = $key . '=' . $v2;
307 $pairs[] = $key . '=' . $value;
311 // Return the pairs, concated with &
312 return implode('&', $pairs);
316 * Returns the base string of this request
318 * The base string defined as the method, the url
319 * and the parameters (normalized), each urlencoded
320 * and the concated with &.
322 public function get_signature_base_string() {/*{{{*/
324 $this->get_normalized_http_method(),
325 $this->get_normalized_http_url(),
326 $this->get_signable_parameters()
329 $parts = OAuthUtil::urlencode_rfc3986($parts);
331 return implode('&', $parts);
335 * just uppercases the http method
337 public function get_normalized_http_method() {/*{{{*/
338 return strtoupper($this->http_method);
342 * parses the url and rebuilds it to be
345 public function get_normalized_http_url() {/*{{{*/
346 $parts = parse_url($this->http_url);
348 $port = isset($parts['port']) ? $parts['port'] : null;
349 $scheme = $parts['scheme'];
350 $host = $parts['host'];
351 $path = @$parts['path'];
353 $port or $port = ($scheme == 'https') ? '443' : '80';
355 if (($scheme == 'https' && $port != '443')
356 || ($scheme == 'http' && $port != '80')) {
357 $host = "$host:$port";
359 return "$scheme://$host$path";
363 * builds a url usable for a GET request
365 public function to_url() {/*{{{*/
366 $out = $this->get_normalized_http_url() . "?";
367 $out .= $this->to_postdata();
372 * builds the data one would send in a POST request
374 * TODO(morten.fangel):
375 * this function might be easily replaced with http_build_query()
376 * and corrections for rfc3986 compatibility.. but not sure
378 public function to_postdata() {/*{{{*/
380 foreach ($this->parameters as $k => $v) {
382 foreach ($v as $va) {
383 $total[] = OAuthUtil::urlencode_rfc3986($k) . "[]=" . OAuthUtil::urlencode_rfc3986($va);
386 $total[] = OAuthUtil::urlencode_rfc3986($k) . "=" . OAuthUtil::urlencode_rfc3986($v);
389 $out = implode("&", $total);
394 * builds the Authorization: header
396 public function to_header() {/*{{{*/
397 $out ='Authorization: OAuth realm=""';
399 foreach ($this->parameters as $k => $v) {
400 if (substr($k, 0, 5) != "oauth") continue;
401 if (is_array($v)) throw new OAuthException('Arrays not supported in headers');
402 $out .= ',' . OAuthUtil::urlencode_rfc3986($k) . '="' . OAuthUtil::urlencode_rfc3986($v) . '"';
407 public function __toString() {/*{{{*/
408 return $this->to_url();
412 public function sign_request($signature_method, $consumer, $token) {/*{{{*/
413 $this->set_parameter("oauth_signature_method", $signature_method->get_name());
414 $signature = $this->build_signature($signature_method, $consumer, $token);
415 $this->set_parameter("oauth_signature", $signature);
418 public function build_signature($signature_method, $consumer, $token) {/*{{{*/
419 $signature = $signature_method->build_signature($this, $consumer, $token);
424 * util function: current timestamp
426 private static function generate_timestamp() {/*{{{*/
431 * util function: current nonce
433 private static function generate_nonce() {/*{{{*/
437 return md5($mt . $rand); // md5s look nicer than numbers
441 * util function for turning the Authorization: header into
442 * parameters, has to do some unescaping
444 private static function split_header($header) {/*{{{*/
445 $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
448 while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
449 $match = $matches[0];
450 $header_name = $matches[2][0];
451 $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
452 $params[$header_name] = OAuthUtil::urldecode_rfc3986( $header_content );
453 $offset = $match[1] + strlen($match[0]);
456 if (isset($params['realm'])) {
457 unset($params['realm']);
464 * helper to try to sort out headers for people who aren't running apache
466 private static function get_headers() {/*{{{*/
467 if (function_exists('apache_request_headers')) {
468 // we need this to get the actual Authorization: header
469 // because apache tends to tell us it doesn't exist
470 return apache_request_headers();
472 // otherwise we don't have apache and are just going to have to hope
473 // that $_SERVER actually contains what we need
475 foreach ($_SERVER as $key => $value) {
476 if (substr($key, 0, 5) == "HTTP_") {
477 // this is chaos, basically it is just there to capitalize the first
478 // letter of every word that is not an initial HTTP and strip HTTP
480 $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
488 class OAuthServer {/*{{{*/
489 protected $timestamp_threshold = 300; // in seconds, five minutes
490 protected $version = 1.0; // hi blaine
491 protected $signature_methods = array();
493 protected $data_store;
495 function __construct($data_store) {/*{{{*/
496 $this->data_store = $data_store;
499 public function add_signature_method($signature_method) {/*{{{*/
500 $this->signature_methods[$signature_method->get_name()] =
504 // high level functions
507 * process a request_token request
508 * returns the request token on success
510 public function fetch_request_token(&$request) {/*{{{*/
511 $this->get_version($request);
513 $consumer = $this->get_consumer($request);
515 // no token required for the initial token request
518 $this->check_signature($request, $consumer, $token);
520 $new_token = $this->data_store->new_request_token($consumer);
526 * process an access_token request
527 * returns the access token on success
529 public function fetch_access_token(&$request) {/*{{{*/
530 $this->get_version($request);
532 $consumer = $this->get_consumer($request);
534 // requires authorized request token
535 $token = $this->get_token($request, $consumer, "request");
538 $this->check_signature($request, $consumer, $token);
540 $new_token = $this->data_store->new_access_token($token, $consumer);
546 * verify an api call, checks all the parameters
548 public function verify_request(&$request) {/*{{{*/
549 $this->get_version($request);
550 $consumer = $this->get_consumer($request);
551 $token = $this->get_token($request, $consumer, "access");
552 $this->check_signature($request, $consumer, $token);
553 return array($consumer, $token);
556 // Internals from here
560 private function get_version(&$request) {/*{{{*/
561 $version = $request->get_parameter("oauth_version");
565 if ($version && $version != $this->version) {
566 throw new OAuthException("OAuth version '$version' not supported");
572 * figure out the signature with some defaults
574 private function get_signature_method(&$request) {/*{{{*/
576 @$request->get_parameter("oauth_signature_method");
577 if (!$signature_method) {
578 $signature_method = "PLAINTEXT";
580 if (!in_array($signature_method,
581 array_keys($this->signature_methods))) {
582 throw new OAuthException(
583 "Signature method '$signature_method' not supported try one of the following: " . implode(", ", array_keys($this->signature_methods))
586 return $this->signature_methods[$signature_method];
590 * try to find the consumer for the provided request's consumer key
592 private function get_consumer(&$request) {/*{{{*/
593 $consumer_key = @$request->get_parameter("oauth_consumer_key");
594 if (!$consumer_key) {
595 throw new OAuthException("Invalid consumer key");
598 $consumer = $this->data_store->lookup_consumer($consumer_key);
600 throw new OAuthException("Invalid consumer");
607 * try to find the token for the provided request's token key
609 private function get_token(&$request, $consumer, $token_type="access") {/*{{{*/
610 $token_field = @$request->get_parameter('oauth_token');
611 $token = $this->data_store->lookup_token(
612 $consumer, $token_type, $token_field
615 throw new OAuthException("Invalid $token_type token: $token_field");
621 * all-in-one function to check the signature on a request
622 * should guess the signature method appropriately
624 private function check_signature(&$request, $consumer, $token) {/*{{{*/
625 // this should probably be in a different method
626 $timestamp = @$request->get_parameter('oauth_timestamp');
627 $nonce = @$request->get_parameter('oauth_nonce');
629 $this->check_timestamp($timestamp);
630 $this->check_nonce($consumer, $token, $nonce, $timestamp);
632 $signature_method = $this->get_signature_method($request);
634 $signature = $request->get_parameter('oauth_signature');
635 $valid_sig = $signature_method->check_signature(
643 throw new OAuthException("Invalid signature");
648 * check that the timestamp is new enough
650 private function check_timestamp($timestamp) {/*{{{*/
651 // verify that timestamp is recentish
653 if ($now - $timestamp > $this->timestamp_threshold) {
654 throw new OAuthException("Expired timestamp, yours $timestamp, ours $now");
659 * check that the nonce is not repeated
661 private function check_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/
662 // verify that the nonce is uniqueish
663 $found = $this->data_store->lookup_nonce($consumer, $token, $nonce, $timestamp);
665 throw new OAuthException("Nonce already used: $nonce");
673 class OAuthDataStore {/*{{{*/
674 function lookup_consumer($consumer_key) {/*{{{*/
678 function lookup_token($consumer, $token_type, $token) {/*{{{*/
682 function lookup_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/
686 function new_request_token($consumer) {/*{{{*/
687 // return a new token attached to this consumer
690 function new_access_token($token, $consumer) {/*{{{*/
691 // return a new access token attached to this consumer
692 // for the user associated with this token if the request token
694 // should also invalidate the request token
700 /* A very naive dbm-based oauth storage
702 class SimpleOAuthDataStore extends OAuthDataStore {/*{{{*/
705 function __construct($path = "oauth.gdbm") {/*{{{*/
706 $this->dbh = dba_popen($path, 'c', 'gdbm');
709 function __destruct() {/*{{{*/
710 dba_close($this->dbh);
713 function lookup_consumer($consumer_key) {/*{{{*/
714 $rv = dba_fetch("consumer_$consumer_key", $this->dbh);
718 $obj = unserialize($rv);
719 if (!($obj instanceof OAuthConsumer)) {
725 function lookup_token($consumer, $token_type, $token) {/*{{{*/
726 $rv = dba_fetch("${token_type}_${token}", $this->dbh);
730 $obj = unserialize($rv);
731 if (!($obj instanceof OAuthToken)) {
737 function lookup_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/
738 if (dba_exists("nonce_$nonce", $this->dbh)) {
741 dba_insert("nonce_$nonce", "1", $this->dbh);
746 function new_token($consumer, $type="request") {/*{{{*/
748 $secret = time() + time();
749 $token = new OAuthToken($key, md5(md5($secret)));
750 if (!dba_insert("${type}_$key", serialize($token), $this->dbh)) {
751 throw new OAuthException("doooom!");
756 function new_request_token($consumer) {/*{{{*/
757 return $this->new_token($consumer, "request");
760 function new_access_token($token, $consumer) {/*{{{*/
762 $token = $this->new_token($consumer, 'access');
763 dba_delete("request_" . $token->key, $this->dbh);
768 class OAuthUtil {/*{{{*/
769 public static function urlencode_rfc3986($input) {/*{{{*/
770 if (is_array($input)) {
771 return array_map(array('OAuthUtil','urlencode_rfc3986'), $input);
772 } else if (is_scalar($input)) {
773 return str_replace('+', ' ',
774 str_replace('%7E', '~', rawurlencode($input)));
781 // This decode function isn't taking into consideration the above
782 // modifications to the encoding process. However, this method doesn't
783 // seem to be used anywhere so leaving it as is.
784 public static function urldecode_rfc3986($string) {/*{{{*/
785 return rawurldecode($string);