4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
23 /* Generic exception class
25 class OAuthException extends Exception { // pass
32 function __construct($key, $secret, $callback_url = NULL) {
34 $this->secret = $secret;
35 $this->callback_url = $callback_url;
38 function __toString() {
39 return "OAuthConsumer[key=$this->key,secret=$this->secret]";
44 // access tokens and request tokens
50 * secret = the token secret
52 function __construct($key, $secret) {
54 $this->secret = $secret;
58 * generates the basic string serialization of a token that a server
59 * would respond to request_token and access_token calls with
61 function to_string() {
62 return "oauth_token=" . OAuthUtil::urlencodeRFC3986($this->key) . "&oauth_token_secret=" . OAuthUtil::urlencodeRFC3986($this->secret);
65 function __toString() {
66 return $this->to_string();
70 class OAuthSignatureMethod {
72 public function check_signature(&$request, $consumer, $token, $signature) {
73 $built = $this->build_signature($request, $consumer, $token);
74 return $built == $signature;
78 class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
84 public function build_signature($request, $consumer, $token) {
85 $base_string = $request->get_signature_base_string();
86 $request->base_string = $base_string;
88 $key_parts = array($consumer->secret, ($token) ? $token->secret : "");
90 $key_parts = array_map(array('OAuthUtil', 'urlencodeRFC3986'), $key_parts);
91 $key = implode('&', $key_parts);
92 return base64_encode(hash_hmac('sha1', $base_string, $key, true));
96 class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
98 public function get_name() {
102 public function build_signature($request, $consumer, $token) {
103 $sig = array(OAuthUtil::urlencodeRFC3986($consumer->secret));
106 array_push($sig, OAuthUtil::urlencodeRFC3986($token->secret));
108 array_push($sig, '');
111 $raw = implode("&", $sig);
112 // for debug purposes
113 $request->base_string = $raw;
115 return OAuthUtil::urlencodeRFC3986($raw);
119 class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
121 public function get_name() {
125 protected function fetch_public_cert(&$request) {
126 // not implemented yet, ideas are:
127 // (1) do a lookup in a table of trusted certs keyed off of consumer
128 // (2) fetch via http using a url provided by the requester
129 // (3) some sort of specific discovery code based on request
131 // either way should return a string representation of the certificate
132 throw Exception("fetch_public_cert not implemented");
135 protected function fetch_private_cert(&$request) {
136 // not implemented yet, ideas are:
137 // (1) do a lookup in a table of trusted certs keyed off of consumer
139 // either way should return a string representation of the certificate
140 throw Exception("fetch_private_cert not implemented");
143 public function build_signature(&$request, $consumer, $token) {
144 $base_string = $request->get_signature_base_string();
145 $request->base_string = $base_string;
147 // Fetch the private key cert based on the request
148 $cert = $this->fetch_private_cert($request);
150 // Pull the private key ID from the certificate
151 $privatekeyid = openssl_get_privatekey($cert);
153 // Sign using the key
154 $ok = openssl_sign($base_string, $signature, $privatekeyid);
156 // Release the key resource
157 openssl_free_key($privatekeyid);
159 return base64_encode($signature);
162 public function check_signature(&$request, $consumer, $token, $signature) {
163 $decoded_sig = base64_decode($signature);
165 $base_string = $request->get_signature_base_string();
167 // Fetch the public key cert based on the request
168 $cert = $this->fetch_public_cert($request);
170 // Pull the public key ID from the certificate
171 $publickeyid = openssl_get_publickey($cert);
173 // Check the computed signature against the one passed in the query
174 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
176 // Release the key resource
177 openssl_free_key($publickeyid);
185 private $http_method;
187 // for debug purposes
189 public static $version = '1.0';
191 function __construct($http_method, $http_url, $parameters = NULL) {
192 @$parameters or $parameters = array();
193 $this->parameters = $parameters;
194 $this->http_method = $http_method;
195 $this->http_url = $http_url;
199 * attempt to build up a request from what was passed to the server
201 public static function from_request($http_method = NULL, $http_url = NULL, $parameters = NULL) {
202 $scheme = (! isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") ? 'http' : 'https';
203 @$http_url or $http_url = $scheme . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
204 @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
205 $request_headers = OAuthRequest::get_headers();
206 // let the library user override things however they'd like, if they know
207 // which parameters to use then go for it, for example XMLRPC might want to
210 $req = new OAuthRequest($http_method, $http_url, $parameters);
211 } elseif (isset($request_headers['Authorization']) && substr($request_headers['Authorization'], 0, 5) == "OAuth") {
212 // next check for the auth header, we need to do some extra stuff
213 // if that is the case, namely suck in the parameters from GET or POST
214 // so that we can include them in the signature
215 $header_parameters = OAuthRequest::split_header($request_headers['Authorization']);
216 if ($http_method == "GET") {
217 $req_parameters = $_GET;
218 } else if ($http_method = "POST") {
219 $req_parameters = $_POST;
221 $parameters = array_merge($header_parameters, $req_parameters);
222 $req = new OAuthRequest($http_method, $http_url, $parameters);
223 } elseif ($http_method == "GET") {
224 $req = new OAuthRequest($http_method, $http_url, $_GET);
225 } elseif ($http_method == "POST") {
226 $req = new OAuthRequest($http_method, $http_url, $_POST);
232 * pretty much a helper function to set up the request
234 public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters = NULL) {
235 @$parameters or $parameters = array();
236 $defaults = array("oauth_version" => OAuthRequest::$version,
237 "oauth_nonce" => OAuthRequest::generate_nonce(),
238 "oauth_timestamp" => OAuthRequest::generate_timestamp(),
239 "oauth_consumer_key" => $consumer->key);
240 $parameters = array_merge($defaults, $parameters);
243 $parameters['oauth_token'] = $token->key;
245 return new OAuthRequest($http_method, $http_url, $parameters);
248 public function set_parameter($name, $value) {
249 $this->parameters[$name] = $value;
252 public function get_parameter($name) {
253 return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
256 public function get_parameters() {
257 return $this->parameters;
261 * Returns the normalized parameters of the request
263 * This will be all (except oauth_signature) parameters,
264 * sorted first by key, and if duplicate keys, then by
267 * The returned string will be all the key=value pairs
272 public function get_signable_parameters() {
273 // Grab all parameters
274 $params = $this->parameters;
276 // Remove oauth_signature if present
277 if (isset($params['oauth_signature'])) {
278 unset($params['oauth_signature']);
281 // Urlencode both keys and values
282 $keys = array_map(array('OAuthUtil', 'urlencodeRFC3986'), array_keys($params));
283 $values = array_map(array('OAuthUtil', 'urlencodeRFC3986'), array_values($params));
284 $params = array_combine($keys, $values);
286 // Sort by keys (natsort)
287 uksort($params, 'strnatcmp');
289 // Generate key=value pairs
291 foreach ($params as $key => $value) {
292 if (is_array($value)) {
293 // If the value is an array, it's because there are multiple
294 // with the same key, sort them, then add all the pairs
296 foreach ($value as $v2) {
297 $pairs[] = $key . '=' . $v2;
300 $pairs[] = $key . '=' . $value;
304 // Return the pairs, concated with &
305 return implode('&', $pairs);
309 * Returns the base string of this request
311 * The base string defined as the method, the url
312 * and the parameters (normalized), each urlencoded
313 * and the concated with &.
315 public function get_signature_base_string() {
316 $parts = array($this->get_normalized_http_method(), $this->get_normalized_http_url(),
317 $this->get_signable_parameters());
319 $parts = array_map(array('OAuthUtil', 'urlencodeRFC3986'), $parts);
321 return implode('&', $parts);
325 * just uppercases the http method
327 public function get_normalized_http_method() {
328 return strtoupper($this->http_method);
332 * parses the url and rebuilds it to be
335 public function get_normalized_http_url() {
336 $parts = parse_url($this->http_url);
338 $port = @$parts['port'];
339 $scheme = $parts['scheme'];
340 $host = $parts['host'];
341 $path = @$parts['path'];
343 $port or $port = ($scheme == 'https') ? '443' : '80';
345 if (($scheme == 'https' && $port != '443') || ($scheme == 'http' && $port != '80')) {
346 $host = "$host:$port";
348 return "$scheme://$host$path";
352 * builds a url usable for a GET request
354 public function to_url() {
355 $out = $this->get_normalized_http_url() . "?";
356 $out .= $this->to_postdata();
361 * builds the data one would send in a POST request
363 public function to_postdata() {
365 foreach ($this->parameters as $k => $v) {
366 $total[] = OAuthUtil::urlencodeRFC3986($k) . "=" . OAuthUtil::urlencodeRFC3986($v);
368 $out = implode("&", $total);
373 * builds the Authorization: header
375 public function to_header($realm = "") {
376 $out = 'Authorization: OAuth realm="' . $realm . '"';
378 foreach ($this->parameters as $k => $v) {
379 if (substr($k, 0, 5) != "oauth") continue;
380 $out .= ',' . OAuthUtil::urlencodeRFC3986($k) . '="' . OAuthUtil::urlencodeRFC3986($v) . '"';
385 public function __toString() {
386 return $this->to_url();
389 public function sign_request($signature_method, $consumer, $token) {
390 $this->set_parameter("oauth_signature_method", $signature_method->get_name());
391 $signature = $this->build_signature($signature_method, $consumer, $token);
392 $this->set_parameter("oauth_signature", $signature);
395 public function build_signature($signature_method, $consumer, $token) {
396 $signature = $signature_method->build_signature($this, $consumer, $token);
401 * util function: current timestamp
403 private static function generate_timestamp() {
408 * util function: current nonce
410 private static function generate_nonce() {
414 return md5($mt . $rand); // md5s look nicer than numbers
418 * util function for turning the Authorization: header into
419 * parameters, has to do some unescaping
421 private static function split_header($header) {
422 // remove 'OAuth ' at the start of a header
423 $header = substr($header, 6);
425 // error cases: commas in parameter values?
426 $parts = explode(",", $header);
428 foreach ($parts as $param) {
429 $param = ltrim($param);
430 // skip the "realm" param, nobody ever uses it anyway
431 if (substr($param, 0, 5) != "oauth") continue;
433 $param_parts = explode("=", $param);
435 // rawurldecode() used because urldecode() will turn a "+" in the
436 // value into a space
437 $out[$param_parts[0]] = rawurldecode(substr($param_parts[1], 1, - 1));
443 * helper to try to sort out headers for people who aren't running apache
445 private static function get_headers() {
446 if (function_exists('apache_request_headers')) {
447 // we need this to get the actual Authorization: header
448 // because apache tends to tell us it doesn't exist
449 return apache_request_headers();
451 // otherwise we don't have apache and are just going to have to hope
452 // that $_SERVER actually contains what we need
454 foreach ($_SERVER as $key => $value) {
455 if (substr($key, 0, 5) == "HTTP_") {
456 // this is chaos, basically it is just there to capitalize the first
457 // letter of every word that is not an initial HTTP and strip HTTP
459 $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
468 protected $timestamp_threshold = 300; // in seconds, five minutes
469 protected $version = 1.0; // hi blaine
470 protected $signature_methods = array();
472 protected $data_store;
474 function __construct($data_store) {
475 $this->data_store = $data_store;
478 public function add_signature_method($signature_method) {
479 $this->signature_methods[$signature_method->get_name()] = $signature_method;
482 // high level functions
486 * process a request_token request
487 * returns the request token on success
489 public function fetch_request_token(&$request) {
490 $this->get_version($request);
492 //open up firebug, check RemoteContentRequest Object
493 //the parameter has only oauth_signature but nothing else.all the keys are missing.
494 //failing the get_consumer request.
495 //print_r($request);exit;
496 $consumer = $this->get_consumer($request);
498 // no token required for the initial token request
501 $this->check_signature($request, $consumer, $token);
503 $new_token = $this->data_store->new_request_token($consumer);
509 * process an access_token request
510 * returns the access token on success
512 public function fetch_access_token(&$request) {
513 $this->get_version($request);
515 $consumer = $this->get_consumer($request);
517 // requires authorized request token
518 $token = $this->get_token($request, $consumer, "request");
520 $this->check_signature($request, $consumer, $token);
522 $new_token = $this->data_store->new_access_token($token, $consumer);
528 * verify an api call, checks all the parameters
530 public function verify_request(&$request) {
531 $this->get_version($request);
532 $consumer = $this->get_consumer($request);
533 $token = $this->get_token($request, $consumer, "access");
534 $this->check_signature($request, $consumer, $token);
535 return array($consumer, $token);
538 // Internals from here
542 private function get_version(&$request) {
543 $version = $request->get_parameter("oauth_version");
547 if ($version && $version != $this->version) {
548 throw new OAuthException("OAuth version '$version' not supported");
554 * figure out the signature with some defaults
556 private function get_signature_method(&$request) {
557 $signature_method = @$request->get_parameter("oauth_signature_method");
558 if (! $signature_method) {
559 $signature_method = "PLAINTEXT";
561 if (! in_array($signature_method, array_keys($this->signature_methods))) {
562 throw new OAuthException("Signature method '$signature_method' not supported try one of the following: " . implode(", ", array_keys($this->signature_methods)));
564 return $this->signature_methods[$signature_method];
568 * try to find the consumer for the provided request's consumer key
570 private function get_consumer(&$request) {
571 $consumer_key = @$request->get_parameter("oauth_consumer_key");
572 if (! $consumer_key) {
573 throw new OAuthException("Invalid consumer key");
576 $consumer = $this->data_store->lookup_consumer($consumer_key);
578 throw new OAuthException("Invalid consumer");
585 * try to find the token for the provided request's token key
587 private function get_token(&$request, $consumer, $token_type = "access") {
588 $token_field = @$request->get_parameter('oauth_token');
589 $token = $this->data_store->lookup_token($consumer, $token_type, $token_field);
591 throw new OAuthException("Invalid $token_type token: $token_field");
597 * all-in-one function to check the signature on a request
598 * should guess the signature method appropriately
600 private function check_signature(&$request, $consumer, $token) {
601 // this should probably be in a different method
602 $timestamp = @$request->get_parameter('oauth_timestamp');
603 $nonce = @$request->get_parameter('oauth_nonce');
604 $this->check_timestamp($timestamp);
605 $this->check_nonce($consumer, $token, $nonce, $timestamp);
606 $signature_method = $this->get_signature_method($request);
607 $signature = $request->get_parameter('oauth_signature');
608 $valid_sig = $signature_method->check_signature($request, $consumer, $token, $signature);
610 throw new OAuthException("Invalid signature");
615 * check that the timestamp is new enough
617 private function check_timestamp($timestamp) {
618 // verify that timestamp is recentish
620 if ($now - $timestamp > $this->timestamp_threshold) {
621 throw new OAuthException("Expired timestamp, yours $timestamp, ours $now");
626 * check that the nonce is not repeated
628 private function check_nonce($consumer, $token, $nonce, $timestamp) {
629 // verify that the nonce is uniqueish
630 $found = $this->data_store->lookup_nonce($consumer, $token, $nonce, $timestamp);
632 throw new OAuthException("Nonce already used: $nonce");
638 class OAuthDataStore {
640 function lookup_consumer($consumer_key) {
644 function lookup_token($consumer, $token_type, $token) {
648 function lookup_nonce($consumer, $token, $nonce, $timestamp) {
652 function fetch_request_token($consumer, $token_secret) {
653 // return a new token attached to this consumer
656 function fetch_access_token($token, $consumer) {
657 // return a new access token attached to this consumer for the user
658 // associated with this token if the request token is authorized
659 // should also invalidate the request token
664 /* A very naive dbm-based oauth storage
666 /* @harris, not needed, use AT_
667 class SimpleOAuthDataStore extends OAuthDataStore {
670 function __construct($path = "oauth.gdbm") {
671 $this->dbh = dba_popen($path, 'c', 'gdbm');
674 function __destruct() {
675 dba_close($this->dbh);
678 function lookup_consumer($consumer_key) {
679 $rv = dba_fetch("consumer_$consumer_key", $this->dbh);
683 $obj = unserialize($rv);
684 if (! ($obj instanceof OAuthConsumer)) {
690 function lookup_token($consumer, $token_type, $token) {
691 $rv = dba_fetch("${token_type}_${token}", $this->dbh);
695 $obj = unserialize($rv);
696 if (! ($obj instanceof OAuthToken)) {
702 function lookup_nonce($consumer, $token, $nonce, $timestamp) {
703 if (dba_exists("nonce_$nonce", $this->dbh)) {
706 dba_insert("nonce_$nonce", "1", $this->dbh);
711 function new_token($consumer, $type = "request") {
713 $secret = time() + time();
714 $token = new OAuthToken($key, md5(md5($secret)));
715 if (! dba_insert("${type}_$key", serialize($token), $this->dbh)) {
716 throw new OAuthException("doooom!");
721 function new_request_token($consumer, $token_secret = null) {
722 return $this->new_token($consumer, "request");
725 function new_access_token($token, $consumer) {
726 $token = $this->new_token($consumer, 'access');
727 dba_delete("request_" . $token->key, $this->dbh);
735 public static function urlencodeRFC3986($string) {
736 return str_replace('+', ' ', str_replace('%7E', '~', rawurlencode($string)));
740 // This decode function isn't taking into consideration the above
741 // modifications to the encoding process. However, this method doesn't
742 // seem to be used anywhere so leaving it as is.
743 public static function urldecodeRFC3986($string) {
744 return rawurldecode($string);